使用Lambda表达式调用通用方法(以及仅在运行时已知的类型)

SDR*_*yes 15 c# generics lambda expression expression-trees

您可以使用Lambda表达式对象将lambda表示为表达式.

如果在运行时只知道用于泛型方法签名的类型,如何创建表示泛型方法调用的Lambda表达式对象

例如:

我想创建一个Lambda表达式对象来调用: public static TSource Last<TSource>( this IEnumerable<TSource> source )

但我只知道TSource运行时的内容.

dtb*_*dtb 27

static Expression<Func<IEnumerable<T>, T>> CreateLambda<T>()
{
    var source = Expression.Parameter(
        typeof(IEnumerable<T>), "source");

    var call = Expression.Call(
        typeof(Enumerable), "Last", new Type[] { typeof(T) }, source);

    return Expression.Lambda<Func<IEnumerable<T>, T>>(call, source)
}
Run Code Online (Sandbox Code Playgroud)

要么

static LambdaExpression CreateLambda(Type type)
{
    var source = Expression.Parameter(
        typeof(IEnumerable<>).MakeGenericType(type), "source");

    var call = Expression.Call(
        typeof(Enumerable), "Last", new Type[] { type }, source);

    return Expression.Lambda(call, source)
}
Run Code Online (Sandbox Code Playgroud)