c# - 不使用 GetMethods 获取泛型方法

标签 c# .net generics reflection

我想获取方法System.Linq.Queryable.OrderyBy<T, TKey>(the IQueryable<T> source, Expression<Func<T,TKey>> keySelector)方法,但我一直想出空值。

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.

有没有人有什么见解?我不想循环遍历 GetMethods结果。

最佳答案

已解决(通过破解 LINQ)!

我在研究同样的问题时看到了你的问题。在找不到好的解决方案后,我萌生了查看LINQ表达式树的想法。这是我想出的:

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

编辑:如果您在编译时不知道类型,这里是获取方法的方法:

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(Program) 替换为 typeof(WhateverClassYouDeclareTheseMethodsIn)。

关于c# - 不使用 GetMethods 获取泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/269578/

相关文章:

java - 为什么不能分配 I <?将类型> 扩展到 <类型>?

c# - 获取 MySql 上的最后一行列

java - Java 中泛型类型和使用接口(interface)作为类型的区别

java - 通配符泛型类型和泛型类型之间未经检查的转换

c# - 方法订阅与 lambda 委托(delegate)订阅 - 哪个以及为什么?

c# - 拖放动态创建的快捷方式

.net - 抽象企业应用程序中的数据连接层和表示层

c# - 如何在sql c#中增加一个整数

c# - 动态查询 azure 表

c# - 如何使用 LINQ 从表中给定值找到范围之间的最高数字