【发布时间】:2019-04-12 09:49:48
【问题描述】:
我想用这样的一种通用方法创建各种类型的委托。
public static object Boo(params object[] args) {
return null;
}
MethodInfo boo = /* MethodInfo of Boo */
// Boo's arg.Length should be `0`
Action action = (Action)Delegate.CreateDelegate(typeof(Action), null, boo);
Func<int> action2 = (Func<int>)Delegate.CreateDelegate(typeof(Func<int>), null, boo);
Func<string, string> action3 = (Func<string, string>)Delegate.CreateDelegate(typeof(Func<string, string>), null, boo);
所以,如果你像这样调用action3
var ret = action3.Invoke("booo");
Boo 的 args.Length 应该是 1,ret 是 null。
在 C# 中可以吗?
- 没有
dynamic、generic或linq.exprssion抱歉。
更新
这个应该用Reflection完成。以上 3 名代表只是示例。委托的类型将在运行时决定。
【问题讨论】:
标签: c# .net reflection