检查方法与给定Delegate的兼容性?

在C#代码中,如何检查给定方法是否可以由特定委托类型表示?

我首先根据我的类型知识尝试了一些东西:

// The delegate to test against. void TargetDelegate(string msg); // and... var methodInfo = Type.GetMethod(..); // obtain the MethodInfo instance. // try to test it typeof(TargetDelegate).IsAssignableFrom(methodInfo.GetType()); 

但这只涉及类型而不是方法 – 它总是错误的。

我倾向于相信答案在于Delegate类型,但我现在只是在FCL游荡。 任何帮助,将不胜感激。

我试试:

 Delegate.CreateDelegate(typeof(TargetDelegate), methodInfo, false) != null 

这将尝试创建委托并在失败时返回null。 如果它返回null,则表示无法创建委托。 如果它返回任何其他内容,则委托必须正常。

我不知道reflection库中有一个方法可以做到这一点。

我认为这不会太难。 直接案例的规则是必须存在从方法的返回类型到委托的返回类型的表示保留转换,并且必须存在从每个委托的参数类型到每个方法的参数类型的表示保留转换。 也就是说,正如您所期望的那样,兼容性关系在返回类型和参数类型的逆变中协变的

有更复杂的案例涉及curried委托,但我认为你可能不想进入那些,除非你这样做是为函数式语言编写编译器。 (你这样做是为函数式语言编写一个编译器吗?)

可能有更优雅的方式,但您可以尝试创建委托,并检查exception:

http://msdn.microsoft.com/en-us/library/ms228976.aspx

说你有

  private delegate int MyDelegate(string a); private int Foo(string a) { } MethodInfo mFoo = this.GetType().GetMethod("Foo"); var @delegate = Delegate.CreateDelegate(typeof (MyDelegate), mFoo, false); if(@delegate!= null) { // compatible } else { // not compatible }