【发布时间】:2013-11-13 21:02:39
【问题描述】:
虽然我知道更改 String.Empty 的值是个坏主意,但我不明白为什么我不能这样做。
要明白我的意思,请考虑以下类:
public class SomeContext
{
static SomeContext(){}
public static readonly string Green = "Green";
public static readonly SomeContext Instance = new SomeContext();
private SomeContext(){}
public readonly string Blue = "Blue";
public static void PrintValues()
{
Console.WriteLine(new { Green, Instance.Blue, String.Empty }.ToString());
}
}
我有一个小控制台应用程序,它试图操纵这三个只读字段。它可以成功将 Blue 和 Green 变成 Pink,但 Empty 保持不变:
SomeContext.PrintValues();
/// prints out : { Green = Green, Blue = Blue, Empty = }
typeof(SomeContext).GetField("Blue").SetValue(SomeContext.Instance, "Pink");
typeof(SomeContext).GetField("Green", BindingFlags.Public | BindingFlags.Static).SetValue(null, "Pink");
typeof(String).GetField("Empty", BindingFlags.Public | BindingFlags.Static).SetValue(null, "Pink");
SomeContext.PrintValues();
/// prints out : { Green = Pink, Blue = Pink, Empty = }
为什么?
最初,我还问为什么String.Empty 不是一个常数。我找到了这部分问题的答案on another post 并删除了这部分问题)。
注意:没有一个“重复”对这个问题有明确的答案,这就是我问这个问题的原因。
【问题讨论】:
-
这可能会回答这个问题:stackoverflow.com/questions/16618302/…
-
简答:你正在改变
System.String.Empty。问题是您检查System.String.Empty的当前值的代码已损坏,因为您违反了它的不变量。开始违反系统不变量,没有什么可以依赖。 -
我注意到
Getvalue返回 "Pink" 虽然访问字段返回 "" -
见How do I draw attention to old unanswered questions。如果您发现有一个问题没有得到解答,解决办法就是不要再问了。考虑在重复的帖子上设置赏金。
-
@Servy - 他们问题的意图不同。这三个都讨论了相同的基本代码行。但是,每个问题都有非常不同的原因。如果我把他们的问题改成和我的一样,我就是在歪曲他们的问题。看看它们,如果你有不同的想法,请告诉我。
标签: c# .net reflection constants immutability