在c#中,我想用空字符串初始化一个字符串值。

我该怎么做呢? 什么是正确的方法,为什么?

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

http://blogs.msdn.com/b/brada/archive/2003/04/22/49997.aspx:

As David implies, there difference between String.Empty and "" are pretty small, but there is a difference. "" actually creates an object, it will likely be pulled out of the string intern pool, but still... while String.Empty creates no object... so if you are really looking for ultimately in memory efficiency, I suggest String.Empty. However, you should keep in mind the difference is so trival you will like never see it in your code... As for System.String.Empty or string.Empty or String.Empty... my care level is low ;-)

其他回答

我个人更喜欢“”,除非有很好的理由去做更复杂的事情。

几乎每个开发者都知道“”是什么意思。我个人就遇到过String。第一次是空的,必须花一些时间搜索谷歌来确定它们是否真的是完全相同的东西。

我喜欢用绳子。空字符串。空的,因为你可以使用它而不需要包含一个using System;在你的档案里。

至于在字符串上选择“”。空,这是个人喜好,应该由你的团队决定。

我没有什么区别。最后一个是打字最快的:)

我本来不想插嘴的,但我发现这里有一些错误的信息。

我个人更喜欢字符串。这是个人喜好,我会根据具体情况服从与我合作的任何团队的意愿。

正如其他人所提到的,字符串和字符串之间根本没有区别。Empty和String.Empty。

此外,这是一个鲜为人知的事实,使用“”是完全可以接受的。在其他环境中,“”的每个实例都将创建一个对象。然而,. net会实习它的字符串,因此未来的实例将从实习池中提取相同的不可变字符串,任何性能损失都可以忽略不计。来源:布拉德·艾布拉姆斯。