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

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

string willi = string.Empty;

or

string willi = String.Empty;

or

string willi = "";

还是别的什么?


当前回答

如果你想恶作剧某人,在他们的代码中加入“‍”。这不是空字符串,它是“\u200D”。你不能用string.Empty欺骗别人。

其他回答

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

(编辑)

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

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

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

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

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

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

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

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

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

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

在查看幕后代码时,您也看不到任何不同。唯一的区别在于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