在C#中,我想用一个空字符串初始化一个字符串值。
我应该怎么做? 正确的方法是什么,为什么?
string willi = string.Empty;
要么
string willi = String.Empty;
要么
string willi = "";
或者是什么?
#1楼
没有人提到在VisualStudio中,字符串的颜色编码与字符串不同。 这对于可读性很重要。 另外,小写通常用于vars和type,不是什么大问题,但String.Empty是常量而不是var或type。
#2楼
从性能和代码生成的角度来看,确实没有什么区别。 在性能测试中,它们之间来回切换得更快,只有几毫秒。
在查看幕后代码时,您实际上也看不到任何区别。 唯一的区别在于IL,即string.Empty使用操作码ldsfld和""使用操作码ldstr ,但这仅是因为string.Empty是静态的,并且两个指令都执行相同的操作。 如果查看所生产的装配,则完全相同。
C#代码
private void Test1()
{
string test1 = string.Empty;
string test11 = test1;
}
private void Test2()
{
string test2 = "";
string test22 = test2;
}
IL代码
.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
#3楼
我个人更喜欢“”,除非有充分理由要更复杂一些。
#4楼
以上任何一项。
有很多很多更好的东西值得赞美。 例如哪种颜色的树皮最适合一棵树,我认为模糊的棕色和淡淡的青苔色。
#5楼
我使用第三个,但在其他两个中,第一个似乎不太奇怪。 string是String的别名,但是在分配中看到它们会感到不舒服。