我经常使用String.Empty
作为占位符,它相当于""
。我的问题是,为什么const
不像String.Empty
?它们的编译方式相同。
// Good
private const string example = "";
// Bad
private const string example = String.Empty;
String.Empty
中的什么使它不能与const
一起使用
String.Empty
是不是一个常量,它只是readonly
字段。由于它是readonly
字段(在编译时是而不是),它不能被赋值给常量。
http://referencesource.microsoft.com/mscorlib/系统/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;