string.Empty 和 "" 并不总是可以互换的

在 C# 中,大多数情况下 "" 和 string.Empty 可以互换使用。比如:

string s = "";
string s2 = string.Empty;

if (s == string.Empty) {
  
// 
}

但是我发现有一种情况下只能是用常数形式: "", 而不能使用 string.Empty 这个静态变量。就是在标签(Attribute) 的构造器里面:

这个代码是正确的:
[Default("")]
public string Name {
  
get return name; }
  
set { name = value; }
}

这个是错误的,无法通过编译:
[Default(string.Empty)]
public string Name {
  
get return name; }
  
set { name = value; }
}

错误信息是:
error CS0182: 属性参数必须是常数表达式、typeof 表达式或数组创建表达式

其他地方我并未发现类似的例子。

顺便提一下,判定为空字符串的几种写法,按照性能从高到低的顺序是:

s.Length == 0  优于 s == string.Empty  优于 s == "" 

这个结论来自于:
http://www.cnblogs.com/allenlooplee/archive/2004/11/11/62805.html
原文地址:https://www.cnblogs.com/RChen/p/236073.html