简体   繁体   中英

Reflection: Cast PropertyInfo to List<obj>

As the title says, then I'm trying to cast a PropertyInfo to its "original" type, which is List<obj> in my case.

I've tried the code below without luck:

(List<obj>)pInfo.GetValue(pInfo, null)

(List<obj>)pInfo.GetValue(typeof<obj>, null)

It simply throws me an exception:

TargetException was unhandled: Object does not match target type.

I'm sure that I'm overlooking something extremely simple, but I cant figure out what.

The first parameter is the target object:

var list = (List<object>)prop.GetValue(obj,null);

Personally, though, I might be tempted to use the non-generic API here; generics and reflection rarely mix well:

var list = (IList)prop.GetValue(obj,null);

This:

(List<obj>)pInfo.GetValue(pInfo, null)

is wrong, the first argument to GetValue should be the object you're reading the property of, not the PropertyInfo itself.

You need to pass in the object you want to get the value for and not the type. Something like this.

List<obj> object ...

(List<obj>) pInfo.GetValue( object, null );

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