在运行时已知类型创建委托类型

2023-09-04 01:14:23 作者:听说微笑能让人疯掉°

我如何可以创建一个只知道在运行时?类型的一个代表。

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 ?

推荐答案

我怀疑你想要的 防爆pression.GetFuncType 因为这样做的一个简单的方法你的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 这比代表更具体的虽然 1 ,因为你根本不知道该类型在编译时。您可能会使用动态不过,这将使它更容易地调用委托:

You can't have a compile-time type for getter that's more specific than Delegate though1, 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);

1 正如评论指出的那样,你的可以的强制转换为 MulticastDelegate ,但它实际上并不买你任何事情。

1 As noted in comments, you could cast to MulticastDelegate, but it wouldn't actually buy you anything.