如何使用动态类型创建Lambda表达式

时间:2018-10-19 13:28:03

标签: c# generics lambda reflection dynamic-typing

我的程序将在运行时获取服务名称和方法名称,并通过创建基于lambda表达式的func来动态执行该方法。

public static Func<object,object,object> CreateLambdaExpression2(string tService, string methodName)
{
    var inputServiceType = Type.GetType(tService);
    var methodInfo = inputServiceType.GetMethod(methodName);
    var inputType = methodInfo.GetParameters().First().ParameterType;
    var outputType = methodInfo.ReturnParameter.ParameterType;

    var instance = Expression.Parameter(inputServiceType, "serviceInstance");
    var input = Expression.Parameter(inputType, "inputData");
    var call = Expression.Call(instance, methodInfo, input);

    var lambdaFunc = Expression.Lambda<Func<object,object, object>>(call, instance, input).Compile(); //<= this line throws the error.
    return lambdaFunc;
}

但不会,它将在运行时引发错误

var compiledMethod = ServiceMapper.CreateLambdaExpression2(tService,"Get");

var serviceInstance = new TestDemoService();
var inputData = new TestDemoPersonRequest()
{
    Id = 555
};
var result = compiledMethod(serviceInstance, inputData);
  

System.ArgumentException:'类型的ParameterExpression   'UnitTests.ITestDemoService'不能用于以下参数的委托参数   键入“ System.Object”

是否可以为Expression.Lambda指定类型?

Expression.Lambda<Func<object,object, object>>

Expression.Lambda<Func<inputServiceType ,inputType , outputType >>

1 个答案:

答案 0 :(得分:0)

您的表达式缺少类型转换。要使其编译,您需要将object显式转换为inputServiceType,依此类推。尝试以下代码:

var objType = typeof(object);
var instance = Expression.Parameter(objType, "serviceInstance");
var input = Expression.Parameter(objType, "inputData");
var call = Expression.Call(
    Expression.Convert(instance, inputServiceType), // convert first arg 
    methodInfo,
    Expression.Convert(input, inputType)); // and second
var body = Expression.Convert(call, objType); // and even return type

var lambdaFunc = Expression.Lambda<Func<object, object, object>>(body, instance, input).Compile();
return lambdaFunc;

尝试here


编辑,您可以使其更加安全:

public static Func<TService, TInput, TReturn>
    CreateTypedLambdaExpression<TService, TInput, TReturn>(
        string methodName)
{
    var inputServiceType = typeof(TService);
    var methodInfo = inputServiceType.GetMethod(methodName);
    var inputType = typeof(TInput);

    // now you need to check if TInput is equal to methodInfo.GetParameters().First().ParameterType
    // same check for return type

    var instance = Expression.Parameter(inputServiceType, "serviceInstance");
    var input = Expression.Parameter(inputType, "inputData");
    var call = Expression.Call(instance, methodInfo, input);

    var lambdaFunc = Expression.Lambda<Func<TService, TInput, TReturn>>(call, instance, input);
    return lambdaFunc.Compile();
}

用法:

var func = CreateTypedLambdaExpression<Program, bool, int>("TestMethod");
var result = func(service, false);