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).
Having:
You can do:
So, I suppose that you have the
MethodInfofor someDisposemethod in your class (heremi, simply throughGetMethod(string)). Then you’ll need to get an InterfaceMapping Structure object for theIDisposableimplementation in the declaring type (hereDisposableObject) through Type.GetInterfaceMap Method . There you haveTargetMethodsreferencing the methods really implementing the interface. So, we only need to check whether your reference equals tom.TargetMethods[0]asIDisposabledeclares only one method.From MSDN:
One remark: if your class could implement
IDisposableexplicitly, thenm.TargetMethods[0]would reference the explicit implemetation. So, I’m not sure whether there is any way to get it’sMethodInfoexcept theInterfaceMapping(See Use Reflection to find Methods that implement explicit interfaces). This situation could be error prone. Check it for your specific issue.