How to get the value of fieldInfo into a generic base type

17 Views Asked by At

C#. I have the following classes:

public class SomeDerivedClass : SomeSuperClass 
{

}
public class Game  : SomeSuperClass 
{
    public List<SomeDerivedClass> inventory_changes = new List<SomeDerivedClass>();
}

public class SomeSuperClass
{
    public virtual void SomeMethod()
    {
        FieldInfo[] fields = GetType().GetFields();

        foreach (FieldInfo fieldInfo in fields)
        {
            if ((fieldInfo.FieldType.IsGenericType) && (fieldInfo.FieldType.GetGenericTypeDefinition() == typeof(System.Collections.Generic.List<>)) && (fieldInfo.FieldType.GetGenericArguments()[0].IsSubclassOf(typeof(SomeSuperClass))))
            {
                List<SomeSuperClass> superclassList = fieldInfo.GetValue(this) as List<SomeSuperClass>;
                List<SomeDerivedClass> derivedClassList = fieldInfo.GetValue(this) as List<SomeDerivedClass>;

                Assert.IsNotNull(superclassList);
                Assert.IsNotNull(derivedClassList);

            }
        }
    }
}

If I instantiate the Game class, and call SomeMethod the following superclass asssertion would fail

Assert.IsNotNull(superclassList); //This fails

while the derived class asssertion would pass:

Assert.IsNotNull(derivedClassList); //This passes

I want to get that field as a list of the SuperClass, not the Derived class.

0

There are 0 best solutions below