vendredi 14 août 2020

Why I can rewrite static readonly field after field initiaization by reflection?

As we know the static constructor is called the first time the class is called.

We now have a class:

static class Demo
{
    private readonly static int _intValue;

    static Demo ()
    {
        _intValue = 5;
    }
}

The constructor will be called when the Demo is accessed. The value 5 will be assigned to the _intValue readonly field. After that, we can once again set the value through reflection:

typeof (Demo)
  .GetField ("_ intValue", BindingFlags.Static | BindingFlags.NonPublic)
  .SetValue (null, 567);

Why value 5 can be overwritten? Isn't it already initialized in the constructor? Why isn't System.FieldAccessException thrown?

Tested in NET Core 3.1. Full example https://dotnetfiddle.net/4DsJ6H





Aucun commentaire:

Enregistrer un commentaire