samedi 23 mai 2020

Why does my static field become null when accessed later?

I have following code:

public abstract class Base {
    private static FieldInfo usersField;

    private object users;

    internal static void InitType(Type type) {
        // usersField == null
        usersField = type.GetField("users");
        // usersField != null
    }

    protected internal virtual void InitInstance(object instance) {
        // usersField == null; again?!
        this.users = usersField.GetValue(instance);
    }
}

public class A : Base {}

In order to initialize it, I execute these two instructions in an unspecified order (A instance may be created first and vice-versa):

Base.InitType(/* reflection type I want to access */);
a = new A(); // private static A a; // Note that this works normally, it is never null when I set it.

Some time later, I call a.InitInstance(/* reflection instance I want to access */) but it fails because my previously-initialized usersField becomes null.

I don't understand why this is happening. I tried checking the AppDomain as suggested in this answer but it is the same in both methods, Unity Root Domain. I also tried making sure that I hold an instance of A before I call InitType() with no success.

While there is a possibility that the external library is reloaded between my InitType() and InitInstance() calls, it is highly unlikely that the engine reloads the whole assembly - it should only call a library-internal method to do the reload.

What am I missing here? Surely usersField object can't be garbage-collected when I hold a reference to it, right?





Aucun commentaire:

Enregistrer un commentaire