Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if method implements IDisposable.Dispose with reflection

Tags:

c#

reflection

aop

Is there a more formal/failsafe way to check whether a System.Reflection.MethodInfo refers to a class' implementation of IDisposable.Dispose than the following?

System.Reflection.MethodInfo methodInfo;
methodInfo = ...; //methodInfo obtaining code here
bool isDisposeMethod = methodInfo.Name == "Dispose";

I already know the class implements IDisposable and thus that Dispose exists, but I'm using a PostSharp aspect that should perform special functionality when Dispose is called (compared to any other class method).

like image 415
Fabian Tamp Avatar asked Nov 26 '12 00:11

Fabian Tamp


1 Answers

Having:

class DisposableObject : IDisposable
{
    public void Dispose()
    {
        //...
    }
}

You can do:

Type t = typeof(DisposableObject);

InterfaceMapping m = t.GetInterfaceMap(typeof(IDisposable));
MethodInfo mi = t.GetMethod("Dispose");

Console.WriteLine(mi == m.TargetMethods[0]); //true

So, I suppose that you have the MethodInfo for some Dispose method in your class (here mi, simply through GetMethod(string)). Then you'll need to get an InterfaceMapping Structure object for the IDisposable implementation in the declaring type (here DisposableObject) through Type.GetInterfaceMap Method . There you have TargetMethods referencing the methods really implementing the interface. So, we only need to check whether your reference equals to m.TargetMethods[0] as IDisposable declares only one method.

From MSDN:

InterfaceMapping Structure

Retrieves the mapping of an interface into the actual methods on a class that implements that interface.

Use the InterfaceMapping structure when a type implements interface methods that use method names other than those specified by the interface, or when a type implements multiple interfaces which have a method with the same name.

To obtain an InterfaceMapping structure, use the Type.GetInterfaceMap method.


One remark: if your class could implement IDisposable explicitly, then m.TargetMethods[0] would reference the explicit implemetation. So, I'm not sure whether there is any way to get it's MethodInfo except the InterfaceMapping (See Use Reflection to find Methods that implement explicit interfaces). This situation could be error prone. Check it for your specific issue.

like image 86
horgh Avatar answered Sep 19 '22 14:09

horgh