gpt4 book ai didi

c# - 制作 lambda 表达式以从泛型类调用方法

转载 作者:行者123 更新时间:2023-11-30 23:12:28 24 4
gpt4 key购买 nike

我有这些简单的界面:

public interface IQuery<TResult> { }

public interface IQueryHandler<in TQuery, out TResult>
where TQuery : IQuery<TResult> {
TResult Handle(TQuery query);
}

并且有一些实现。我正在尝试创建一个表达式树来调用 Handle指定处理程序上的方法。我的意思是:

var query = new MyQuery(); // which MyQuery implements IQuery<int>
object handler = _someServiceProvider
.Get<IQueryHandler<MyQuery, int>>();

此外,还有一个 MyQueryHandler :

public class MyQueryHandler : IQueryHandler<MyQuery, int> {
public int Handle(MyQuery query) { return 20; }
}

现在,我正在尝试创建一个 Func<object, MyQuery, int>像这样调用:

var func = GetMethod<MyQuery, int>(handler);
var result = func(handler, query);

这是我的 GetMethod实现:

    private Func<object, TQuery, TResult> GetMethod<TQuery, TResult>(object obj)
where TQuery : IQuery<TResult> {

var methodInfo = obj.GetType().GetMethod(nameof(IQueryHandler<TQuery, TResult>.Handle));

var insExp = Expression.Parameter(typeof(object), "ins");

var inputExp = Expression.Parameter(typeof(TQuery), "query");

var instanceExp = Expression.Variable(obj.GetType(), "instance");

var assExp = Expression.Assign(instanceExp, Expression.Convert(insExp, obj.GetType()));

var castExp = Expression.Convert(inputExp, methodInfo.GetParameters()[0].ParameterType);

var callExp = Expression.Call(instanceExp, methodInfo, castExp);

var blockExp = Expression.Block(new Expression[] {
insExp,
inputExp,
instanceExp,
assExp,
castExp,
callExp
});

var func =
Expression.Lambda<Func<object, TQuery, TResult>>(
blockExp,
insExp,
inputExp).Compile();
return func;
}

但是,当我尝试编译 Lambda ,我得到这个错误:

An exception of type 'System.InvalidOperationException' occurred in System.Core.dll but was not handled in user code

Additional information: variable 'instance' of type 'Namespace.MyQueryHandler' referenced from scope '', but it is not defined

我哪里错了?我错过了什么?你有什么主意吗?提前致谢。

最佳答案

据我所知,您正在尝试编写此函数:

TResult f(object ins, TQuery query)
{
var instance = (MyQueryHandler)ins;
return instance.Handle(query);
}

要使用表达式树执行此操作,您必须在 Expression.Block 中声明变量,但随后仅指定上面的两个语句,而不是所有子表达式:

var blockExp = Expression.Block(new[] { instanceExp }, new Expression[] {
assExp,
callExp
});

但一个更简单的选择是改为编写以下函数:

TResult f(object ins, TQuery query)
{
return ((MyQueryHandler)ins).Handle(query);
}

看起来像这样:

var callExp = Expression.Call(
Expression.Convert(insExp, obj.GetType()), methodInfo, castExp);

var func =
Expression.Lambda<Func<object, TQuery, TResult>>(
callExp,
insExp,
inputExp).Compile();

关于c# - 制作 lambda 表达式以从泛型类调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44098384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com