【发布时间】:2018-08-02 12:16:59
【问题描述】:
我有以下课程
public interface ISomeInterface
{
void DoThings();
}
public class SomeImplementation1 : ISomeInterface
{
public void DoThings() { /*..*/ }
}
public class Base
{
public static ISomeInterface field;
}
public class Derived1 : Base
{
static Derived1() { field = new SomeImplementation(); }
}
Type derivedType = // retrieve a type derived from Base
FieldInfo fieldInfo = derivedType.GetField("field", BindingFlags.Static | BindingFlags.Public); // is null
ISomeInterface a = (ISomeInterface) fieldInfo.GetValue(null);
a.DoThings();
所以我想得到一个在 Base 中定义但在 Derived 中设置的静态字段值。同时我没有对初始化的 Derived 对象的引用,只有它的类型。
当我尝试查找对应的字段信息时,结果为空。据我了解,静态字段绑定到定义它们的类。这就是为什么在给定派生类的情况下我无法获得字段引用。
有没有办法解决这个问题?
一些背景:我使用 Unity。 Class Base 是一个 MonoBehaviour,我不想实例化它,因为它会导致性能开销。同时,我想访问一些绑定到其派生类并由 ISomeInterface 的实现表示的逻辑。
【问题讨论】:
-
typeof(Base).GetField(...)之类的呢?
标签: c# reflection static