c# - 使用运行时已知的类型创建委托(delegate)

标签 c# .net delegates

如何创建仅在运行时才知道类型的委托(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/

相关文章:

C# 破解 : assignment to "this"

c# - 自动重启windows服务

c# - .NET 中的传统循环与 Action 委托(delegate)

c# - 字符串未被识别为有效的 DateTime ParseExact

c# - LINQ 选择异步方法的模拟

c# - 如何使委托(delegate)线程成为STA

c# - 回调函数

c# - 使用 GroupBy 计算对象列表中具有相同属性值的对象

c# - 避免 Task 和 Task<T> 的重复方法

c# - 常量字符串数组