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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

字符串是System的同义词。字符串类型,它们是相同的。

值也是相同的:字符串。空==字符串。空== ""

我不会在代码中使用字符常量“”,而是字符串。空或字符串。空-更容易看到程序员的意思。

在字符串和字符串之间,我更喜欢小写字符串,因为我曾经使用Delphi很多年,Delphi风格是小写字符串。

所以,如果我是你的老板,你会写字符串。空

其他回答

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

编译器应该让它们在长期运行时都是一样的。选择一个标准,这样你的代码就容易阅读,并坚持下去。

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 ;-)

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

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

最好的代码是没有代码:

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

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