mardi 11 août 2015

Read-only Violation Not Handled as Expected

Given the code below, I'm very surprised that an exception is not thrown and would like to know why not. I have a class that has a readonly field that is initialized in the constructor. I then use reflection to get the FieldInfo and call the SetValue method. This results in the otherwise read-only field being writable. My question is why is this allowed to happen?

If this is allowed to happen, that means the readonly keyword is purely for compile-time checking and has very little bearing on the actual instruction generation, I would assume. Thanks in advance for your insights.

public class SomeType
{
    public readonly int RONumber;

    public int LocalMember;

    public SomeType()
    {
        RONumber = 32;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var st = new SomeType
        {
            LocalMember = 8
        };

        var ron1 = st.RONumber;

        var type = typeof(SomeType);

        var ronField = type.GetField("RONumber");

        ronField.SetValue(st, 405);

        var ron2 = st.RONumber; // ron2 is 405!
    }
}





Aucun commentaire:

Enregistrer un commentaire