为什么在创建const字符串变量时不能使用String.Empty?

Gre*_*reg 4 c#

我经常使用String.Empty占位符,相当于"".所以我的问题,为什么不const喜欢String.Empty?他们编译相同.

// Good
private const string example = "";

// Bad
private const string example = String.Empty;
Run Code Online (Sandbox Code Playgroud)

是什么String.Empty让它无法与a一起使用const.

Dmi*_*nko 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;
Run Code Online (Sandbox Code Playgroud)