C# 使用运行时已知的类型创建委托

C# 使用运行时已知的类型创建委托,c#,.net,delegates,C#,.net,Delegates,如何创建仅在运行时已知类型的委托 我想做以下工作: Type type1 = someObject.getType(); Type type2 = someOtherObject.getType(); var getter = (Func<type1, type2>)Delegate.CreateDelegate( typeof(Func<,>).MakeGenericType(type1, type2), someMethodInfo); type1=

如何创建仅在运行时已知类型的委托

我想做以下工作:

Type type1 = someObject.getType();
Type type2 = someOtherObject.getType();   

var getter = (Func<type1, type2>)Delegate.CreateDelegate(
    typeof(Func<,>).MakeGenericType(type1, type2), someMethodInfo);
type1=someObject.getType();
Type type2=someOtherObject.getType();
var getter=(Func)Delegate.CreateDelegate(
typeof(Func).MakeGenericType(type1,type2),someMethodInfo;
如何实现类似的功能?

我想您希望使用一种更简单的方法来执行
typeof(…)。MakeGenericType
操作

var delegateType = Expression.GetFuncType(type1, type2);
Delegate getter = Delegate.CreateDelegate(delegateType, someMethodInfo);
您不能为
getter
设置比
Delegate
though1更具体的编译时类型,因为您在编译时根本不知道该类型。但是,您可能会使用
动态
,这将使调用委托更容易:

dynamic getter = ...;
var result = getter(input);


1如注释中所述,您可以强制转换为
MulticastDelegate
,但它实际上不会为您购买任何东西。

我怀疑您希望以更简单的方式执行
typeof(…)。MakeGenericType
操作

var delegateType = Expression.GetFuncType(type1, type2);
Delegate getter = Delegate.CreateDelegate(delegateType, someMethodInfo);
您不能为
getter
设置比
Delegate
though1更具体的编译时类型,因为您在编译时根本不知道该类型。但是,您可能会使用
动态
,这将使调用委托更容易:

dynamic getter = ...;
var result = getter(input);


1如评论中所述,您可以强制转换为
多播委托
,但实际上它不会为您购买任何东西。

您可以为此创建一个通用方法:

public Func<T1, T2> GetFunc<T1, T2>(T1 Object1, T2 Object2, MethodInfo Method)
{
    return (Func<T1, T2>)Delegate.CreateDelegate(typeof(Func<,>).MakeGenericType(typeof(T1), typeof(T2)), Method);
}
public Func GetFunc(T1 Object1、T2 Object2、MethodInfo方法)
{
return(Func)Delegate.CreateDelegate(typeof(Func).MakeGenericType(typeof(T1),typeof(T2)),方法);
}
我敢打赌,你可以用同样的哲学和方法来避免所有这些反射的东西

Obs:只有T1和T2是类型化变量时,这才有效。如果它们是
对象
,您将得到一个
Func
。但是……如果你给这个方法的对象也是
对象
,那就没有问题了。
根据您的场景,您甚至可以始终使用
Func

您可以为此创建一个通用方法:

public Func<T1, T2> GetFunc<T1, T2>(T1 Object1, T2 Object2, MethodInfo Method)
{
    return (Func<T1, T2>)Delegate.CreateDelegate(typeof(Func<,>).MakeGenericType(typeof(T1), typeof(T2)), Method);
}
public Func GetFunc(T1 Object1、T2 Object2、MethodInfo方法)
{
return(Func)Delegate.CreateDelegate(typeof(Func).MakeGenericType(typeof(T1),typeof(T2)),方法);
}
我敢打赌,你可以用同样的哲学和方法来避免所有这些反射的东西

Obs:只有T1和T2是类型化变量时,这才有效。如果它们是
对象
,您将得到一个
Func
。但是……如果你给这个方法的对象也是
对象
,那就没有问题了。
根据您的场景,您甚至可以始终使用
Func

您不能<编译时不知道code>Func
。您的变量
getter
必须具有编译时已知的编译时类型。那可能是
System.Delegate
。你不能<编译时不知道code>Func
。您的变量
getter
必须具有编译时已知的编译时类型。这可能是
System.Delegate
+1:sicopic up在没有阅读问题或答案的情况下从我这里投票。尽我的职责!(开玩笑)
多播委托
更具体;p+1:请不要看问题或答案,直接投我一票。尽我的职责!(开玩笑)
多播委托
更具体;P