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. 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. 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. Class Base is a MonoBehaviour and I don't want to instantiate it as it will result in performance overhead. At the same time, I want to access some logic bound to its derived classes and represented by implementations of ISomeInterface.
Aucun commentaire:
Enregistrer un commentaire