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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

虽然差别非常非常小,但差别仍然存在。

""在String时创建一个对象。空则不然。但是这个对象只创建一次,如果代码中有另一个"",就会从字符串池中引用它。 String和String是一样的,但是我建议使用String。空(以及字符串。格式字符串。因为点表示法表示的是类,而不是操作符,而且类以大写字母开头符合c#编码标准。

其他回答

从性能和代码生成的角度来看,确实没有什么区别。在性能测试中,它们在哪个比另一个更快之间来回切换,而且仅以毫秒计。

在查看幕后代码时,您也看不到任何不同。唯一的区别在于IL,即字符串。空使用操作码ldsfld ""使用ldstr操作码,但这只是因为字符串。Empty是静态的,两个指令做相同的事情。 如果你看一下生产出来的组件,它是完全一样的。

c#代码

private void Test1()
{
    string test1 = string.Empty;    
    string test11 = test1;
}

private void Test2()
{
    string test2 = "";    
    string test22 = test2;
}

有密码

.method private hidebysig instance void 
          Test1() cil managed
{
  // Code size       10 (0xa)
  .maxstack  1
  .locals init ([0] string test1,
                [1] string test11)
  IL_0000:  nop
  IL_0001:  ldsfld     string [mscorlib]System.String::Empty
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  stloc.1
  IL_0009:  ret
} // end of method Form1::Test1
.method private hidebysig instance void 
        Test2() cil managed
{
  // Code size       10 (0xa)
  .maxstack  1
  .locals init ([0] string test2,
                [1] string test22)
  IL_0000:  nop
  IL_0001:  ldstr      ""
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  stloc.1
  IL_0009:  ret
} // end of method Form1::Test2

汇编代码

        string test1 = string.Empty;
0000003a  mov         eax,dword ptr ds:[022A102Ch] 
0000003f  mov         dword ptr [ebp-40h],eax 

        string test11 = test1;
00000042  mov         eax,dword ptr [ebp-40h] 
00000045  mov         dword ptr [ebp-44h],eax 
        string test2 = "";
0000003a  mov         eax,dword ptr ds:[022A202Ch] 
00000040  mov         dword ptr [ebp-40h],eax 

        string test22 = test2;
00000043  mov         eax,dword ptr [ebp-40h] 
00000046  mov         dword ptr [ebp-44h],eax 

最好的代码是没有代码:

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

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

一个不同之处在于,如果使用切换大小写语法,就不能编写大小写字符串。空:因为它不是一个常数。您将得到一个编译错误:期望一个常量值

更多信息请看这个链接: string-empty-versus-empty-quotes

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

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