C#中静态只读变量和集合的奇怪行为

时间:2012-06-30 18:20:15

标签: c# oop static readonly

我在命名空间Global

中创建了以下类
namespace Global
{
    public static class Status
    {
        public static readonly char Active;
        public static readonly char Suspended;
        public static readonly char Terminiated;
        public static readonly char Deleted;

        private static readonly Dictionary<char, string> statusCollection;
        public static Dictionary<char, string> StatusCollection 
        { 
            get 
            { 
                return statusCollection; 
            }
        }

        static Status()
        {
            statusCollection = new Dictionary<char, string>();
            statusCollection.Add('A', "Active");
            statusCollection.Add('S', "Suspended");
            statusCollection.Add('T', "Terminated");
            statusCollection.Add('D', "Deleted");

            Active = 'A';
            Suspended = 'S';
            Terminiated = 'T';
            Deleted = 'D';
        }
    }

    public class a
    {
        public void add()
        {
            //How to make this collection readonly
            Status.StatusCollection.Add('N', "asd"); 

            Status.Active = 'M'; //Throws a compile time exception, changes not allowed
        }
    }
}

奇怪的行为当我尝试在即时窗口中更新Status.Active时,我希望该值不会改变,但允许更改。这是否意味着我们可以通过反射或运行时更改readonly变量的值?

1 个答案:

答案 0 :(得分:5)

是的,您可以通过Reflection在运行时更改readonly属性的值。这是一个非常简单的POC:

public class Program
{
    private static readonly string Foo = "Bar";

    static void Main()
    {
        typeof(Program)
            .GetField("Foo", BindingFlags.Static | BindingFlags.NonPublic)
            .SetValue(null, "new value");
        Console.WriteLine(Foo);
    }
}

当您运行此控制台应用程序时,它将打印:

new value