c# - 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() { ... }
谢谢您的帮助。
解决方案
如果我正确理解你的问题
给定
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);
虽然关于你这样做或需要这样做的方式,我不确定
推荐阅读
- jboss - JBoss CodeReady 远程调试失败
- android - Android - 具有多个底部导航菜单的导航组件
- javascript - 使用 nodejs/express 服务器和 mysql 数据库的 React 应用程序在首次访问主页时不会立即加载数据。mysql连接相关
- apache-spark - 为什么 Spark SQL 在某些字符串 concat() 中添加双引号,而在其他字符串中不添加双引号?我不想在数字字段周围加上引号
- ios - Json 错误 typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue:
- php - 使用这种在 Laravel 中使用相同的登录页面对用户进行身份验证的方法是否存在任何安全问题?
- html - 如何使身体的背景图像变暗?
- c++ - WorkerW下定位Windows
- ruby-on-rails - breadcrumbs_on_rails 缺少必需的键:[:id]
- sql - SUM ROW NUMBER 以获得基金的交易量和事件类型