uni*_*uni 2 c# generics reflection iqueryable
这可能听起来愚蠢的,但我不能得到MethodInfo的Queryable.Join(...).我想得到它,因为如何在泛型方法调用中使用Type变量(C#)
它有2个可用的方法签名和我想没有的IEqualityComparer的一个,所以我需要指定Type[]在GetMethod.
我写了类似的东西
MethodInfo joinMethod = typeof( Queryable ).GetMethod( "Join", new Type[] { typeof(IEnumerable<>), typeof(Expression<Func<>>), typeof(Expression<Func<>>), typeof(Expression<Func<>>)});
Run Code Online (Sandbox Code Playgroud)
但它不起作用.我无法在上面指定泛型中的类型,因为它们是Type从外部传递的(这就是我需要这种反射的原因).
谁能告诉我怎么样?谢谢!
使用泛型和反射可能有点单调乏味.你最好的选择(保持简单)是使用GetMethods和过滤你想要的东西.
//Overly simplified
MethodInfo joinMethod = typeof(Queryable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(m => m.Name == "Join" && m.GetParameters().Length == 5)
.First();
Run Code Online (Sandbox Code Playgroud)
鉴于此,此时MethodInfo不可调用.您需要使用它来制作它的通用版本joinMethod.MakeGenericMethod(/*type array*/).在您的情况下,您需要使用4种类型:TOuter,TInner,TKey,TResult.
var genericJoinMethod = joinMethod.MakeGenericMethod(new Type[]{your types here});
Run Code Online (Sandbox Code Playgroud)
现在你可以genericJoinMethod按照你的期望使用.
据我所知,如果您在编译时不知道类型,那么这是唯一的方法.
编辑:
鉴于你的评论,我认为它应该是这样的:
MethodInfo joinMethod = typeof(Queryable)
.GetMethods(BindingFlags.Static | BindingFlags.Public)
.Where(m => m.Name == "Join" && m.GetParameters().Length == 5)
.First();
var genericJoinMethod = joinMethod.MakeGenericMethod(typeof(TType), typeof(TType), JoinKeyType, typeof(TType));
result = genericJoinMethod.Invoke( result, new object[] { result, items, OuterKeySelector, InnerKeySelector, ResultSelector } );
Run Code Online (Sandbox Code Playgroud)