开发者

Check compatibility of a method with a given Delegate?

In C# code, how do I check if a given method can be represented by a particular delegate type?

I first tried something, based on my Type knowledge, along the lines of:

// 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());

but that deals with only Types and not methods - it will always be false.

My inclination开发者_StackOverflow社区 is to believe the answer lies in the Delegate Type, but I'm just wandering around the FCL at this point. Any help would be appreciated.


I'd try:

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

This will try to create the delegate and return null on failure. If it return null, it should mean that the delegate was not able to be created. If it returns anything else, the delegate must be OK.


I am not aware of a method in the reflection library that does that.

I don't think it would be too hard though. The rule for straightforward cases is that there must be a representation-preserving conversion from the method's return type to the delegate's return type, and there must be a representation-preserving conversion from each of the delegate's parameter types to each of the method's parameter types. That is, the compatibility relation is covariant in return type and contravariant in parameter type, as you'd expect.

There are more complex cases involving curried delegates but I think you probably don't want to get into those unless you are doing this to write a compiler for a functional language. (Are you doing this to write a compiler for a functional language?)


There may be a more elegant way, but you could try creating the delegate, and check for an exception:

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


say you have

   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
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜