我有以下代码:
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
对象。为什么我的反射信息对象被删除?
我认为原因是使用Virtual关键字。调用虚拟方法时,也许您需要再次重新分配变量。