调用使用Lambda表达式泛型方法(只有在运行时已知的类型) [英] Calling a Generic Method using Lambda Expressions (and a Type only known at runtime)

查看:596
本文介绍了调用使用Lambda表达式泛型方法(只有在运行时已知的类型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以使用 Lambda表达式对象代表一个lambda作为表达式。



你如何创建的 Lambda表达式对象代表一个通用的方法调用,如果你只知道 - 即在运行时使用泛型方法的签名工具的类型?



例如:



我要创建的 Lambda表达式对象调用:
公共静态TSource尾< TSource>(这个IEnumerable的< TSource>源)



不过,我才知道什么 TSource 在运行时。


解决方案

 静态表达式来; Func键<&IEnumerable的LT; T> ;, T>> CreateLambda< T>()
{
无功源= Expression.Parameter(
的typeof(IEnumerable的< T>),源);

VAR调用= Expression.Call(
typeof运算(可枚举),上,新类型[] {typeof运算(T)},源);

返回Expression.Lambda< Func键< IEnumerable的< T> ;, T>>(打电话,源)
}

 静态LambdaExpression CreateLambda(type类型)
{
无功源= Expression.Parameter(
的typeof(IEnumerable的<方式>)MakeGenericType(类型),源);

VAR调用= Expression.Call(
typeof运算(可枚举),上,新类型[] {}类型,源);

返回Expression.Lambda(打电话,源)
}


You can use Lambda Expression Objects to represent a lambda as an expression.

How do you create a Lambda Expression Object representing a generic method call, if you only know the type -that you use for the generic method signature- at runtime?

For example:

I want to create a Lambda Expression Objects to call: public static TSource Last<TSource>( this IEnumerable<TSource> source )

But I only know what TSource is at runtime.

解决方案

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)
}

or

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)
}

这篇关于调用使用Lambda表达式泛型方法(只有在运行时已知的类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆