2013-05-03 97 views
10

有没有因为他们都在做打印屏幕上的长度同一工作中使用{0}+之间的区别:{0}和+之间有什么区别?

Console.WriteLine("Length={0}", length); 
Console.WriteLine("Length=" + length); 
+2

最终结果没有任何区别,但在实现方式上肯定存在差异。 – 2013-05-03 20:30:09

+0

是的,C#区分大小写,所以我们不能判断长度是否与长度不同。 – 2013-05-03 20:31:31

+1

但是如果你想要更多的信息,第一行将在Intern池中有Length = {0},但是第二行将在Intern池中。 – 2013-05-03 20:32:30

回答

1

是有区别的。

例如:

Console.WriteLine("the length is {0} which is the length", length); 
Console.WriteLine("the length is "+length+" which is the length"); 

+连接两个字符串,{0}是要插入一个字符串的占位符。

+1

有没有*真的*串联和插入之间的区别?我看到的唯一区别是便利。 – Daniel 2013-05-03 20:31:42

+2

我会说格式*而不是*插入*,因为它确实是'String.Format(...)'。 – 2013-05-03 20:32:11

+0

@Daniel我认为值得区分 - 否则有些人可能会觉得你可以在任何地方使用“{0}”占位符语法*。但是,您只能使用具有代码来解释字符串格式的方法。 – 2013-05-03 20:38:19

0

{n}其中n >= 0允许您以字符串中出现的顺序替换值。

string demo = "demo", example = "example"; 
Console.WriteLine("This is a {0} string used as an {1}", demo, example); 

+让你两个或多个字符串拼接在一起。

Console.WriteLine("This is a " + demo + " string used as an " + example); 
+0

连接将实际上结束如下:'string.Concat(“这是一个”,演示,“字符串用作”示例);'编译器完成后。 – asawyer 2013-05-03 20:35:31

2

第二行将创建一个字符串并将字符串输出。 第一行将使用composite formatting,如string.Format。

Here是使用复合格式的一些很好的理由。

1

{n}是一个可用于多个选项的占位符。 其中n是一个数字

在你的例子中它会有所作为,最终结果将是两个字符串串联的结果。然而,在类似

var firstName = "babba"; 
var lastName ="abba"; 
var dataOfBirth = new Date(); 

Console 
    .Write(" Person First Name : {0} | Last Name {1} }| Last Login : {2:d/M/yyyy HH:mm:ss}", 
      firstName, 
      secondName, 
      dateOfBirth); 

它提供了一个易于阅读界面,方便进行格式化

30

在您简单的例子,有没有什么区别。但是有很好的理由可以选择格式化({0})选项:它使得国际化软件的本地化变得更加容易,并且使第三方编辑现有字符串变得更容易。

试想一下,比如你正在编写产生此错误消息编译:

"Cannot implicitly convert type 'int' to 'short'" 

你真的想编写代码

Console.WriteLine("Cannot implicitly convert type '" + sourceType + "' to '" + targetType + "'"); 

?天哪,没有。你希望把这个字符串转换成资源:

"Cannot implicitly convert type '{0}' to '{1}'" 

,然后写

Console.WriteLine(FormatError(Resources.NoImplicitConversion, sourceType, targetType)); 

,因为你有自由决定要改变这种状况到:

"Cannot implicitly convert from an expression of type '{0}' to the type '{1}'" 

或者

"Conversion to '{1}' is not legal with a source expression of type '{0}'" 

这些选择可以稍后由英语专业学生进行,无需更改代码。

您也可以将这些资源翻译成其他语言,再次而不更改代码

现在开始始终使用格式化字符串;当你需要编写可正确使用字符串资源的本地化软件时,你已经习惯了。

+0

感谢解释 – AK1 2013-05-03 21:28:57

+1

我在阅读StackOverflow和之前的Joel博客的5年中使用格式化字符串的最佳参数。 – bricklayer137 2013-05-04 00:05:13

相关问题