我尝试使用void返回类型编译表达式以使用对象返回类型进行委托。我想在这种情况下获得空值。
var inputArg0 = Expression.Parameter(typeof(object), "arg0");
var inputArg1 = Expression.Parameter(typeof(CancellationToken), "arg1");
var inputArg0Converted = Expression.Convert(inputArg0, inputArg0Type);
var instanceExpression = Expression.Constant(instance);
var call = Expression.Call(instanceExpression, methodInfo, inputArg0Converted, inputArg1);
var lambda = Expression.Lambda<Func<object, CancellationToken, object>>(call, inputArg0, inputArg1);
var _delegate = lambda.Compile();
// works
public string Ping(object e, CancellationToken cancellationToken)
{
return "OK";
}
// can't compile this MethodInfo to Func<object, CancellationToken, object>
public void Update(ObjectChangedEvent e, CancellationToken cancellationToken)
{
// do stuff
}
答案 0 :(得分:3)
对于void返回类型,您可以使用Action
而不是Func
来试试这个:
Action<object, CancellationToken, object>
答案 1 :(得分:1)
您可以将动作方法包装在返回null的Func中,如下所示:
Func<object, CancellationToken, object> l = (object e, CancellationToken d ) =>
{
Update((ObjectChangedEvent) e, d);
return null;
};