AK1*_*AK1 10 c# string string-formatting
使用{0}和之间是否有任何区别,+因为他们在屏幕上打印长度的工作相同:
Console.WriteLine("Length={0}", length);
Console.WriteLine("Length=" + length);
Run Code Online (Sandbox Code Playgroud)
Eri*_*ert 30
在你琐碎的例子中,没有区别.但是有很好的理由更喜欢使用formatted({0})选项:它使国际软件的本地化变得更加容易,并且使第三方编辑现有字符串变得更加容易.
想象一下,例如,您正在编写一个生成此错误消息的编译器:
"Cannot implicitly convert type 'int' to 'short'"
Run Code Online (Sandbox Code Playgroud)
你真的想写代码吗?
Console.WriteLine("Cannot implicitly convert type '" + sourceType + "' to '" + targetType + "'");
Run Code Online (Sandbox Code Playgroud)
?天哪没有.您想将此字符串放入资源中:
"Cannot implicitly convert type '{0}' to '{1}'"
Run Code Online (Sandbox Code Playgroud)
然后写
Console.WriteLine(FormatError(Resources.NoImplicitConversion, sourceType, targetType));
Run Code Online (Sandbox Code Playgroud)
因为那时您可以自由决定是否要将其更改为:
"Cannot implicitly convert from an expression of type '{0}' to the type '{1}'"
Run Code Online (Sandbox Code Playgroud)
要么
"Conversion to '{1}' is not legal with a source expression of type '{0}'"
Run Code Online (Sandbox Code Playgroud)
这些选择可以在以后由英语专业人员进行,而无需更改代码.
您也可以将这些资源翻译成其他语言,而无需更改代码.
立即开始使用格式化字符串; 当你需要编写适当使用字符串资源的可本地化软件时,你已经习惯了.
它们是有区别的。
前任:
Console.WriteLine("the length is {0} which is the length", length);
Console.WriteLine("the length is "+length+" which is the length");
Run Code Online (Sandbox Code Playgroud)
+连接两个字符串,{0}是要插入的字符串的占位符。
| 归档时间: |
|
| 查看次数: |
442 次 |
| 最近记录: |