简体   繁体   English

通过反射获取父级的静态字段值

[英]Get parent's static field value via reflection

I have the following classes 我有以下课程

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();

So I want to get a static field value that is defined in Base, but set in Derived. 所以我想获得在Base中定义但在Derived中设置的静态字段值。 At the same time I don't have a reference to initialized Derived object and have only its type. 同时,我没有对初始化的派生对象的引用,而只有其类型。

When I try to find a corresponding field info, the result is null. 当我尝试查找相应的字段信息时,结果为null。 As I understand, static fields are bound to the class where they were defined in. That's why I can't get field reference given a derived class. 据我了解,静态字段绑定到定义它们的类。这就是为什么在给定派生类的情况下我无法获得字段引用的原因。

Is there a way around this? 有没有解决的办法?

Some context: I work with Unity. 一些背景:我与Unity合作。 Class Base is a MonoBehaviour and I don't want to instantiate it as it will result in performance overhead. Class Base是MonoBehaviour,我不想实例化它,因为它会导致性能开销。 At the same time, I want to access some logic bound to its derived classes and represented by implementations of ISomeInterface. 同时,我想访问一些绑定到其派生类并由ISomeInterface的实现表示的逻辑。

the type indicated by derivedType has no field field . derivedType指示的类型没有字段field This is statically bound to the Base -class. 这是静态绑定到Base -class。 So you have two opportunities 所以你有两个机会

  1. use the base-type: 使用基本类型:

     Type derivedType = // retrieve a type derived from Base FieldInfo fieldInfo = derivedType.BaseType.GetField("field", BindingFlags.Static | BindingFlags.Public); // is nul 
  2. flatten the hierarchy to get all fields from base-classes also: 展平层次结构以从基类中获取所有字段:

     Type derivedType = // retrieve a type derived from Base FieldInfo fieldInfo = derivedType.GetField("field", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); 

Apart from this there´s no need to use reflection in your case, you don´t need an instance to access a static field. 除此之外,您无需使用反射,也不需要实例来访问静态字段。 That´s the entire use of static . 这就是static的全部用法。 Just use this: 只需使用此:

ISomeInterface a = Base.field;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM