我经常使用String.Empty
作为占位符,相当于""
。所以我的问题是,为什么const
不喜欢String.Empty
?他们编译相同。
// Good
private const string example = "";
// Bad
private const string example = String.Empty;
String.Empty
中的内容使其无法与const
一起使用。
答案 0 :(得分:9)
String.Empty
不是常量,它只是readonly
字段。由于它是readonly
字段(在编译时不已知),因此无法将其分配给常量。
http://referencesource.microsoft.com/#mscorlib/system/string.cs,c9f70a27facb27cf
...
//We need to call the String constructor so that the compiler doesn't mark this as a literal.
//Marking this as a literal would mean that it doesn't show up as a field which we can access
//from native.
public static readonly String Empty;