找一个通用的方法,而无需使用的getMethods [英] Get a generic method without using GetMethods
问题描述
我想获得方法 System.Linq.Queryable.OrderyBy< T,TKEY的>(在IQueryable的< T>来源,例pression< Func键< T,TKEY的>>的KeySelectors )
的方法,但我一直想出空。
I want to get the method System.Linq.Queryable.OrderyBy<T, TKey>(the IQueryable<T> source, Expression<Func<T,TKey>> keySelector)
method, but I keep coming up with nulls.
var type = typeof(T);
var propertyInfo = type.GetProperty(group.PropertyName);
var propertyType = propertyInfo.PropertyType;
var sorterType = typeof(Func<,>).MakeGenericType(type, propertyType);
var expressionType = typeof(Expression<>).MakeGenericType(sorterType);
var queryType = typeof(IQueryable<T>);
var orderBy = typeof(System.Linq.Queryable).GetMethod("OrderBy", new[] { queryType, expressionType }); /// is always null.
没有人有任何见解?我想preFER通过的getMethods
结果不循环。
推荐答案
解决(因黑客行为LINQ)!
Solved (by hacking LINQ)!
我看到你的问题,同时研究了同样的问题。发现没有很好的解决方案后,我有了主意,看看LINQ EX pression树。这就是我想出了:
I saw your question while researching the same problem. After finding no good solution, I had the idea to look at the LINQ expression tree. Here's what I came up with:
public static MethodInfo GetOrderByMethod<TElement, TSortKey>()
{
Func<TElement, TSortKey> fakeKeySelector = element => default(TSortKey);
Expression<Func<IEnumerable<TElement>, IOrderedEnumerable<TElement>>> lamda
= list => list.OrderBy(fakeKeySelector);
return (lamda.Body as MethodCallExpression).Method;
}
static void Main(string[] args)
{
List<int> ints = new List<int>() { 9, 10, 3 };
MethodInfo mi = GetOrderByMethod<int, string>();
Func<int,string> keySelector = i => i.ToString();
IEnumerable<int> sortedList = mi.Invoke(null, new object[] { ints,
keySelector }
) as IEnumerable<int>;
foreach (int i in sortedList)
{
Console.WriteLine(i);
}
}
输出:10 3 9
output: 10 3 9
编辑:这里是如何获得的方法,如果你不知道在编译时的类型:
Here is how to get the method if you don't know the type at compile-time:
public static MethodInfo GetOrderByMethod(Type elementType, Type sortKeyType)
{
MethodInfo mi = typeof(Program).GetMethod("GetOrderByMethod", Type.EmptyTypes);
var getOrderByMethod = mi.MakeGenericMethod(new Type[] { elementType,
sortKeyType });
return getOrderByMethod.Invoke(null, new object[] { }) as MethodInfo;
}
请务必更换的typeof(节目)用typeof(WhateverClassYouDeclareTheseMethodsIn)。
Be sure to replace typeof(Program) with typeof(WhateverClassYouDeclareTheseMethodsIn).
这篇关于找一个通用的方法,而无需使用的getMethods的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!