如何创建仅在运行时才知道类型的委托(delegate)?
我想做以下事情:
Type type1 = someObject.getType();
Type type2 = someOtherObject.getType();
var getter = (Func<type1, type2>)Delegate.CreateDelegate(
typeof(Func<,>).MakeGenericType(type1, type2), someMethodInfo);
我怎样才能实现类似的目标?
最佳答案
我怀疑你想要 Expression.GetFuncType
作为做你的typeof(...).MakeGenericType
的一种更简单的方法手术。
var delegateType = Expression.GetFuncType(type1, type2);
Delegate getter = Delegate.CreateDelegate(delegateType, someMethodInfo);
getter
不能有编译时类型这比 Delegate
更具体虽然1,因为您在编译时根本不知道该类型。您可能会使用 dynamic
但是,这将更容易调用委托(delegate):dynamic getter = ...;
var result = getter(input);
1 如评论中所述,您可以转换为
MulticastDelegate
,但它实际上不会给你买任何东西。
关于c# - 使用运行时已知的类型创建委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16484092/