c# - 为什么我不能更改 String.Empty 的值?

标签 c# .net reflection constants immutability

虽然我知道更改 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并删除了那部分问题)。

注意:没有一个“重复”对这个问题有决定性的答案,这就是我问这个问题的原因。

最佳答案

您无法更改它,因为您的计算机上装有 .NET 4.5。只需将项目的 Framework Target 设置更改为 3.5,您就会看到它起作用了。

CLR 具有 String.Empty 的内置知识。例如,您会看到 System.String 类从不初始化 Reflector 或 Reference Source。它在 CLR 启动期间完成。 4.5 究竟如何防止修改可见有点难说。您实际上确实修改了字段,只需添加这行代码:

  var s = typeof(String).GetField("Empty", 
             BindingFlags.Public | BindingFlags.Static).GetValue(null);
  Console.WriteLine(s);

您会看到“粉红色”。我的猜测是它被抖动拦截了。但是,我不能为此提供确凿的证据。有先例,例如尝试修改 Decimal.MaxValue,另一个只读静态值。 3.5中也不可更改,抖动识别并直接生成值,无需读取该字段。

我刚发现你悬赏了 another question与完全相同的主题。 280Z28 的帖子非常相似。

关于c# - 为什么我不能更改 String.Empty 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19964254/

相关文章:

c# - 使用属性来约束类型 - .NET

c# - 快速搜索一组元素

.net - 如何在使用 Office 2003 打开 Office 2007 文档时禁用转换消息?

c# - 是否可以包装特定的类或方法并将它们分配给线程?

c# - 如何使用 .NET 反射查找一个类的所有直接子类

c# - 将 Logo 添加到 Orchard 主题的页面

c# - VB.NET/C#:启动ASIO控制面板

c# - 使用二项元组与字典相比有什么优势?

c# - 从 IEnumerable<T> 获取类型 T

java - 如何根据属性的值获取属性的名称?