问题描述
我如何可以创建一个只知道在运行时?类型的一个代表。
How can I create a Delegate with types only known at run time ?
我要做到以下几点:
Type type1 = someObject.getType();
Type type2 = someOtherObject.getType();
var getter = (Func<type1, type2>)Delegate.CreateDelegate(
typeof(Func<,>).MakeGenericType(type1, type2), someMethodInfo);
我如何能实现类似的东西?
How can I achieve something similar ?
推荐答案
我怀疑你想要的因为这样做的一个简单的方法你的typeof(...)。MakeGenericType
操作。
I suspect you want Expression.GetFuncType
as a simpler way of doing your typeof(...).MakeGenericType
operation.
var delegateType = Expression.GetFuncType(type1, type2);
Delegate getter = Delegate.CreateDelegate(delegateType, someMethodInfo);
您不能拥有的编译时间的类型的getter
这比代表更具体的
虽然,因为你根本不知道该类型在编译时。您可能会使用动态
不过,这将使它更容易地调用委托:
You can't have a compile-time type for getter
that's more specific than Delegate
though, because you simply don't know that type at compile-time. You could potentially use dynamic
though, which would make it easier to invoke the delegate:
dynamic getter = ...;
var result = getter(input);
正如评论指出的那样,你的可以的强制转换为 MulticastDelegate
,但它实际上并不买你任何事情。
As noted in comments, you could cast to MulticastDelegate
, but it wouldn't actually buy you anything.
这篇关于在运行时已知类型创建委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!