3

我在命名空间 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通过反射或运行时更改变量的值?

4

1 回答 1

5

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
于 2012-06-30T18:21:57.660 回答