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开发者_JAVA百科:
(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 );
精彩评论