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

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

问题描述

您可以使用 Lambda Expression Objects 表示一个lambda作为表达式。



如何创建一个rel =noreferrer> Lambda Expression Object? >

例如:



我想创建一个 Lambda Expression Objects 调用:
public static TSource Last< TSource>(这个IEnumerable< TSource>来源)



但是我只知道什么 TSource 运行时。

解决方案

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

返回Expression.Lambda< Func< IEnumerable< T>,T>(call,source)
}

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


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天全站免登陆