在。net中,String和。net之间的区别是什么?空和"",他们是可交换的,或者有一些潜在的引用或本地化问题,围绕相等的字符串。空将保证都不是问题?


当前回答

另一个区别是字符串。Empty生成更大的CIL代码。而用于引用“”和String的代码。Empty是相同的长度,编译器不会为string优化字符串连接(参见Eric Lippert的博客文章)。空的参数。以下等价函数

string foo()
{
    return "foo" + "";
}
string bar()
{
    return "bar" + string.Empty;
}

生成这个IL

.method private hidebysig instance string foo() cil managed
{
    .maxstack 8
    L_0000: ldstr "foo"
    L_0005: ret 
}
.method private hidebysig instance string bar() cil managed
{
    .maxstack 8
    L_0000: ldstr "bar"
    L_0005: ldsfld string [mscorlib]System.String::Empty
    L_000a: call string [mscorlib]System.String::Concat(string, string)
    L_000f: ret 
}

其他回答

字符串之间的区别是什么。空和“”,是他们 可以互换

字符串。Empty是一个只读字段,而""是一个编译时常量。他们表现不同的地方有:

c# 4.0或更高版本中的默认参数值

void SomeMethod(int ID, string value = string.Empty)
// Error: Default parameter value for 'value' must be a compile-time constant
{
    //... implementation
}

switch语句中的大小写表达式

string str = "";
switch(str)
{
    case string.Empty: // Error: A constant value is expected. 
        break;

    case "":
        break;

}

属性参数

[Example(String.Empty)]
// Error: An attribute argument must be a constant expression, typeof expression 
//        or array creation expression of an attribute parameter type

""的所有实例都是相同的,被分隔的字符串字面量(或者它们应该是)。因此,每次使用""时,实际上不会在堆上抛出一个新对象,而只是创建一个对相同的内部对象的引用。话虽如此,我还是更喜欢字符串。我认为这使代码更具可读性。

前面的答案对于。net 1.1是正确的(查看他们链接的帖子的日期:2003年)。至于. net 2.0和以后的版本,基本上没有区别。无论如何,JIT最终都会引用堆上相同的对象。

根据c#规范,第2.4.4.5节: http://msdn.microsoft.com/en-us/library/aa691090 (VS.71) . aspx

每个字符串字面值不一定会产生一个新的字符串实例。当两个或多个根据字符串相等运算符(第7.9.7节)等效的字符串字面值出现在同一个程序集中时,这些字符串字面值引用同一个字符串实例。

有人甚至在布拉德·亚伯拉姆的帖子评论中提到了这一点

总之,"" vs. String的实际结果。Empty是nil。JIT最终会弄清楚的。

就我个人而言,我发现JIT比我聪明得多,所以我尽量在微编译器优化方面不太聪明。JIT将展开for()循环,删除冗余代码,内联方法等,在比我或c#编译器之前预期的更好和更合适的时间。让JIT来做它的工作吧:)

上面的答案在技术上是正确的,但你可能真正想要使用的是String.IsNullOrEmpty(s),以获得最好的代码可读性和最小的异常机会。

使用字符串。空而不是""。

This is more for speed than memory usage but it is a useful tip. The "" is a literal so will act as a literal: on the first use it is created and for the following uses its reference is returned. Only one instance of "" will be stored in memory no matter how many times we use it! I don't see any memory penalties here. The problem is that each time the "" is used, a comparing loop is executed to check if the "" is already in the intern pool. On the other side, String.Empty is a reference to a "" stored in the .NET Framework memory zone. String.Empty is pointing to same memory address for VB.NET and C# applications. So why search for a reference each time you need "" when you have that reference in String.Empty?

参考:字符串。Empty和""