在运行时已知类型创建委托 [英] Create delegate with types known at runtime

查看:121
本文介绍了在运行时已知类型创建委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于在运行时已知类型创建委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆