简体   繁体   中英

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 .

So, thanks to @Fildor I figured out the solution:

var en = val as IEnumerable;
foreach (var o in en) {
    (o as BaseClass)?.DoThing();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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