Reputation: 49
Imagine I have several classes of different types with the same property.
I want to make a generic method that should acess the value of the property of those classes.
The following code is invalid and will throw this error :
Cannot resolve method 'GetValue(T)' (...)
.. so what's the proper way to do this?
public static List<int> FooBar<T>(T myObject)
{
var myValue = typeof(T).GetProperty("myList").GetValue(myObject);
return myValue;
}
Upvotes: 1
Views: 84
Reputation: 30545
If you really want to do this with generics, try the code below
return (List<int>)(typeof(T).GetProperty("myList").GetValue(myObject, null))
Upvotes: 1
Reputation: 18975
you can do like this myObject.GetType().GetProperty("myList").GetValue(myObject, null);
Upvotes: 1
Reputation: 1062550
The "proper" way to do this is probably to have a where T : SomeInterfaceOrBaseType
, i.e. the thing that has a myList
member - and then just access it; i.e. return myObject.myList;
interface IFoo {
List<int> myList {get;}
}
public static List<int> FooBar<T>(T myObject) where T : IFoo {
return myObject.myList;
}
But... by the time you've done that, there's not really a need for the method any more, as if the caller knows that the type is an IFoo
, they can do that themselves.
If you must do it via reflection... well, that's hard. It might be easier to just abuse dynamic
:
public static List<int> FooBar<T>(T myObject)
{
dynamic obj = myObject;
List<int> myList = obj.myList;
return myList;
}
Upvotes: 3