How to do a generic call to function based on a Type object? [duplicate]
how do you execute Get, when all you have is: T expressed as a Type object i.e.
Type type=typeof(int);
and arguments param1 and param2?
public void DoCa开发者_开发知识库ll(){
var type=typeof(int);
// object o=Get<type> ("p1","p2"); //<-- wont work (expected)
// *** what should go here? ***
}
public IEnumerable<T> Get<T>(string param1,string param2) {
throw new NotImplementedException();
}
You need to use reflection:
public IEnumerable GetBoxed(Type type, string param1, string param2)
{
return (IEnumerable)this
.GetType()
.GetMethod("Get")
.MakeGenericMethod(type)
.Invoke(this, new[] { param1, param2 });
}
MakeGenericMethod
is the key:
var get = typeof(WhereverYourGetMethodIs).GetMethod("Get");
var genericGet = get.MakeGenericMethod(type);
What's wrong with just using the generic type parameter directly?
public void DoCall(){
IEnumerable<int> integers = Get<int> ("p1","p2");
// ...
}
In the example above the 'T' will be whatever you pass into the Get method and it will also return the same IEnumerable. So if you do the following:
IEnumerable<int> o = Get<int>("p1", "p2");
o will be IEnumerable
but if you want something else, then you just pass in a different Type, hence Generic types.
If possible, you should redefine your Get method to take the type of object as an argument:
public IEnumerable<object> Get(object type, string param1,string param2)
{
}
Then if you really need it, you can rewrite the original generic method as follows:
public IEnumerable<T> Get<T>(string param1,string param2)
{
var result = Get(typeof(T), param1, param2);
return result.Cast<T>();
}
精彩评论