为什么以后访问时我的静态反射场变为空?

问题描述 投票:1回答:1

我有以下代码:

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 {}

为了初始化它,我以未指定的顺序执行这两条指令(A实例可能首先创建,反之亦然:

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.

一段时间后,我打电话给a.InitInstance(/* reflection instance I want to access */),但是它失败了,因为先前初始化的usersField变成了null

我不明白为什么会这样。我尝试按照AppDomain中的建议检查this answer,但在Unity Root Domain这两种方法中都相同。我也尝试确保在调用A之前没有成功持有InitType()的实例。

虽然有可能在我的InitType()InitInstance()调用之间重新加载外部库,但是引擎重新加载整个程序集的可能性很小-它仅应调用库内部方法进行重新加载。

我在这里想念什么?当我持有对usersField对象的引用时,肯定无法对其进行垃圾收集,对吗?

注意:如果我存储的是Type而不是FieldInfo,则可以在FieldInfo中检索InitInstance()并获取users对象。为什么我的反射信息对象被删除?

c# reflection static nullreferenceexception
1个回答
0
投票

我认为原因是使用Virtual关键字。调用虚拟方法时,也许您需要再次重新分配变量。

© www.soinside.com 2019 - 2024. All rights reserved.