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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

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

考虑下面的c#代码…

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

vs

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

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

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

其他回答

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是string的别名,但在赋值中看到它们会让人感觉不舒服。

这个话题已经很老很长了,所以如果在其他地方提到过这种行为,请原谅。(并指出我的答案,包括这个)

如果你使用字符串,我发现编译器的行为有所不同。空引号或双引号。如果你不使用用string初始化的string变量,区别就会显现出来。为空或带双引号。

在初始化字符串的情况下。空,然后编译器警告

CS0219 - The variable 'x' is assigned but its value is never used

永远不会触发,而在使用双引号初始化的情况下,您将获得预期的消息。

这种行为在Connect文章中有解释,链接:https://connect.microsoft.com/VisualStudio/feedback/details/799810/c-warning-cs0219-not-reported-when-assign-non-constant-value

基本上,如果我做对了,他们希望允许程序员用函数的返回值设置一个变量用于调试目的,而不用警告消息来打扰他,因此他们只在常量赋值和字符串的情况下限制警告。空不是常数,而是场。

几年后 微软已经关闭了https://connect .microsoft.com网站,因此没有更多可用的讨论。然而,这篇文章https://learn.microsoft.com/en-us/dotnet/csharp/misc/cs0219有一个有趣的评论,似乎证实了前面的原因:

只有当变量值为a时,编译器才会生成此警告 编译时常量。指定一个非常量表达式或方法 结果的局部变量,使观察这些更容易 调试器中的表达式。它还使结果可达, 在该变量可达时防止垃圾收集。

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

他们在自动生成的文件(如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("")>