我正在尝试理解为什么
string.Empty
是readonly
而不是const
。我看到这个帖子,但我不理解Microsoft在评论中写的内容。正如Jon Skeet在评论中所写的那样,"我不知道 - 老实说,这对我来说没有多少意义......"。
共享源代码基础结构2.0发布。string.cs位于sscli20 \ clr \ src \ bcl \ system \ string.cs中。// The Empty constant holds the empty string value.
//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 = "";
我在这里看不到任何String构造函数的调用,而且它被标记为字面量 - ""
能否有人用简单的语言解释一下这个注释的意思,以及为什么string.Empty
是只读的而不是常量?
更新:
Eric Lippert 在一个已删除的答案中发表了评论:(链接):
我在午餐时问了一位C#老手关于这个问题,他不记得具体为什么做出了这个决定,但猜测可能与内部化有关。
typeof(string).GetField("Empty").SetValue(null, null);
或者typeof(string).GetField("Empty").SetValue(null, " ");
进行调试了,这太无趣了!嘿嘿嘿;嘿嘿嘿嘿嘿嘿嘿;嘿嘿嘿嘿嘿嘿!! - Marc Gravell