asdfasfasdf

在string.Format中使用大括号

在C#中,string.Format是一个非常方便的格式字符串的方法。

比如为了输出Bill is a student.这个句子,就可以使用以下的方法:
string studentName = "Bill";
string.Format("{0} is a student.", studentName);

这样就可以动态的来格式化字符串。

可以发现,大括号是用来格式化字符串用的,也就是说,如果想格式化大括号,肯定是会出问题的。

实际中,编译可以通过,会报出一个运行时错误:字符串格式错误。

解决方法:

用“{{”或者“}}”来输出。

bool isMale = false;
string result = string.Format("get {{ return {0}; }}", isMale);

result的值应该是“get { return false; }”

posted on 2007-05-23 10:55  明达  阅读(1201)  评论(0编辑  收藏  举报

导航