【发布时间】:2018-06-03 04:09:18
【问题描述】:
我正在尝试编写一个表达式树,它可以使用MethodInfo 给出的方法订阅EventInfo 给出的事件。表达式树应该编译成Action<object, object>,其中的参数是事件源对象和订阅对象。 EventInfo 和 MethodInfos 保证兼容。
这是我目前所拥有的:
// Given the following
object Source = /**/; // the object that will fire an event
EventInfo SourceEvent = /**/; // the event that will be fired
object Target = /**/; // the object that will subscribe to the event
MethodInfo TargetMethod = /**/; // the method that will react to the event
// setting up objects involved
var sourceParam = Expression.Parameter(typeof(object), "source");
var targetParam = Expression.Parameter(typeof(object), "target");
var sourceParamCast = Expression.Convert(sourceParam, SourceEvent.DeclaringType);
var targetParamCast = Expression.Convert(targetParam, TargetMethod.DeclaringType);
// Get subscribing method group. This is where things fail
var targetMethodRef = Expression.MakeMemberAccess(targetParamCast, TargetMethod);
// Subscribe to the event
var addMethodCall = Expression.Call(sourceParamCast, SourceEvent.AddMethod, targetMethodRef);
var lambda = Expression.Lambda<Action<object, object>>(addMethodCall, sourceParam, targetParam);
var subscriptionAction = lambda.Compile();
// And then later, subscribe to the event
subscriptionAction(Source, Target);
在调用MakeMemberAccess 时出现以下异常:
ArgumentException:成员 'void theMethodName()' 不是字段或属性
这里的目标是让targetMethodRef 实质上表示在使用方法订阅事件时会出现在+= 右侧的内容。
TLDR:如何创建表达式以将对象上的方法组作为参数传递给表达式树中的函数调用?
【问题讨论】:
标签: c# expression-trees linq-expressions