首页 > 解决方案 > MethodInfo.CreateDelegate 与异步任务返回类型

问题描述

我有这个方法,

public void SomeMethod() { ... }

我可以毫无问题地使用反射创建委托,

var action = (Action)method.CreateDelegate(typeof(Action), this);
...
action.Invoke();

但是,如果我替换void返回async Task类型,我会收到此错误,

Cannot bind to the target method because its signature is not compatible with that of the delegate type.

如果方法是这样的,我找不到如何创建委托并调用它的方法,

public async Task SomeMethod() { ... }

或者像这样,

public async Task<SomeObject> SomeMethod() { ... }

谢谢您的帮助。

标签: c#

解决方案


如果我正确理解你的问题

给定

public async Task SomeBob() { ... }

我猜你正在寻找

MethodInfo method =  //<Some wonderful reflection here>
var bob = (Func<Task>)method.CreateDelegate(typeof(Func<Task>), this);

await bob();

或者

(Func<Task<SomeType>>)method.CreateDelegate(typeof(Func<Task<SomeType>>), this);

虽然关于你这样做或需要这样做的方式,我不确定


推荐阅读