How to use a Type variable in a generic method call (C#)
I have a Type variable t
passed into a method, and I want to use it as a generic parameter when calling IQueryable.Join
like the following
queryResult.Jo开发者_开发问答in<Type1, Type2, t, Type3>( items, outerSelector, innerSelector, ( a, b) => a);
It obviously doesn't work. What should I do to t
in order to achieve what I intended? Thanks!
Basically you've got to call the method with reflection:
- Get the generic method template with
Type.GetMethod
- Call
MakeGenericMethod
passing in your 4 type parameters - Invoke the method passing in the regular arguments
It's a pain :(
I'm not sure of the details of your "type variable," but if the variable is already a generic parameter to the method, you can use it as a generic parameter to Join also:
public void MyMethod<T>()
{
// do some stuff to get queryResult, then
queryResult.Join<Type1, Type2, T, Type3>(items, outerSelector, innerSelector, (a, b) => something);
}
精彩评论