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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

I strongly prefer String.Empty, aside from the other reasons to ensure you know what it is and that you have not accidentally removed the contents, but primarily for internationalization. If I see a string in quotes then I always have to wonder whether that is new code and it should be put into a string table. So every time code gets changed/reviewed you need to look for "something in quotes" and yes you can filter out the empty strings but I tell people it is good practice to never put strings in quotes unless you know it won't get localized.

其他回答

这可能是一个有争议的评论,但是,总的来说,我发现当我与微软保持一致时,我的生活更容易。我们不可能知道他们做事的全部深层原因(我想有时是非常严格的,有时是笨拙的)。

他们在自动生成的文件(如Assembly文件)中使用“”,所以这就是我所做的。事实上,当我尝试用字符串替换任何下面的“”。空,Visual Studio崩溃在我身上。这可能有一个合乎逻辑的解释,但以我有限的知识,如果我只是做他们做的事情,大多数时候,事情都会解决。(反:我知道一些自动生成的文件也使用字符串。空的,这有点打破我的观点。:))

<Assembly: System.Reflection.AssemblyCulture("")>
<Assembly: System.Reflection.AssemblyDescription("")>
<Assembly: System.Reflection.AssemblyFileVersion("1.0.0.0")>
<Assembly: System.Reflection.AssemblyKeyFile("")>
<Assembly: System.Reflection.AssemblyProduct("")>
<Assembly: System.Reflection.AssemblyTitle("")>

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

以上任何一种。

还有很多很多更好的事情可以指手画脚。比如什么颜色的树皮最适合一棵树,我认为是模糊的棕色和淡淡的苔藓。

我在.NET v4.5控制台应用程序中使用以下方法执行了一个简单的测试:

private static void CompareStringConstants()
{
    string str1 = "";
    string str2 = string.Empty;
    string str3 = String.Empty;
    Console.WriteLine(object.ReferenceEquals(str1, str2)); //prints True
    Console.WriteLine(object.ReferenceEquals(str2, str3)); //prints True
}

这表明所有三个变量,即str1, str2和str3,虽然使用不同的语法初始化,但都指向内存中的相同字符串(零长度)对象。

所以在内部它们没有区别。这一切都归结为您或您的团队想要使用哪一个的便利性。字符串类的这种行为在。net框架中被称为字符串实习。Eric Lippert有一篇很好的博客描述了这个概念。

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