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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

最好的代码是没有代码:

编码的基本性质是,作为程序员,我们的任务是认识到我们所做的每一个决定都是一种权衡。从简洁开始。根据测试的需要增加其他维度。

因此,代码越少越好:更喜欢“”而不是字符串。Empty或String.Empty。这两篇文章的篇幅长了六倍,但没有额外的好处——当然也没有额外的清晰度,因为它们表达的信息完全相同。

其他回答

我更喜欢字符串而不是字符串。选择字符串。空而不是“”是选择一个并坚持下去的问题。使用字符串的优点。空是很明显你的意思,你不会不小心复制了不可打印的字符,如“\x003”在你的“”。

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

最好的代码是没有代码:

编码的基本性质是,作为程序员,我们的任务是认识到我们所做的每一个决定都是一种权衡。从简洁开始。根据测试的需要增加其他维度。

因此,代码越少越好:更喜欢“”而不是字符串。Empty或String.Empty。这两篇文章的篇幅长了六倍,但没有额外的好处——当然也没有额外的清晰度,因为它们表达的信息完全相同。

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.

我在.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有一篇很好的博客描述了这个概念。