lundi 28 novembre 2022

How to access list property of derived type through reflection?

Consider this code sample:

public abstract class BaseClass {
    public virtual void DoThing() {
        ...
    }
}

public class DerivedClass {
    public override void DoThing() {
        ...
    }
}

public class SomeClass {
    public List<DerivedClass> MyProp {get; set;}
}

...

// assume we have obj of SomeClass and prop as PropertyInfo of MyProp

var pt = prop.PropertyType;

if (pt.IsGeneric && (pt.GetGenericTypeDefinition() == typeof(List<>)) && (pt.GetGenericArguments()[0].IsSubclassOf(typeof(BaseClass))))
{
    var val = pt.GetValue(obj); // here it is not null 
    var list = val as List<BaseClass>; // list is null
    list?.ForEach(o => o.DoThing());
}

How can I get list of BaseClass and call (probably) overridden method for each of them? As I try to cast property value to list it become null.





Aucun commentaire:

Enregistrer un commentaire