为什么不能't字符串.在创建const字符串变量时使用

本文关键字:字符串 变量 const 创建 为什么 不能 | 更新日期: 2023-09-27 18:01:38

我经常使用String.Empty作为占位符,它相当于""。我的问题是,为什么const不像String.Empty ?它们的编译方式相同。

// Good
private const string example = "";
// Bad
private const string example = String.Empty;

String.Empty中的什么使它不能与const一起使用

为什么不能't字符串.在创建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;