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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

前两种我都可以接受。我将避免使用最后一种方法,因为在引号之间加空格很容易引入错误。这种特殊的缺陷很难通过观察发现。假设没有错别字,所有这些在语义上都是等价的。

(编辑)

另外,为了保持一致性,你可能总是想使用string或string,但这只是我的想法。

其他回答

没有人提到在VisualStudio中字符串的颜色编码与字符串不同。这对可读性很重要。此外,小写通常用于变量和类型,不是什么大问题,而是字符串。Empty是常量,而不是变量或类型。

我认为第二个是“合适的”,但老实说,我不认为这有什么关系。编译器应该足够聪明,可以将其中任何一个编译为完全相同的字节码。我用“myself”。

The empty string is like empty set just a name that everybody uses to call "". Also in formal languages strings created from an alphabet that have zero length are called the empty string. Both set and string have a special symbol for it. Empty string: ε and empty set: ∅. If you want to talk about this zero length string you will call it the empty string so everybody knows exactly what you are referring to. Now in case you name it the empty string why not use string.Empty in code, its shows the intention is explicit. Downside is that it’s not a constant and therefore not available everywhere, like in attributes. (It's not a constant for some technical reasons, see the reference source.)

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

我只是在看一些代码,然后这个问题突然出现在我的脑海里,这个问题是我以前读过的。这当然是可读性的问题。

考虑下面的c#代码…

(customer == null) ? "" : customer.Name

vs

(customer == null) ? string.empty : customer.Name

我个人认为后者不那么模棱两可,也更容易阅读。

正如其他人指出的那样,实际的差异可以忽略不计。