是否有更正式/故障安全的方法来检查 System.Reflection.MethodInfo
是否存在?指类的 IDisposable.Dispose
的实现比下面的?
System.Reflection.MethodInfo methodInfo;
methodInfo = ...; //methodInfo obtaining code here
bool isDisposeMethod = methodInfo.Name == "Dispose";
我已经知道类实现 IDisposable
因此 Dispose
存在,但我使用的是 PostSharp 方面,它应该在 Dispose
时执行特殊功能被调用(与任何其他类方法相比)。
最佳答案
拥有:
class DisposableObject : IDisposable
{
public void Dispose()
{
//...
}
}
你可以这样做:
Type t = typeof(DisposableObject);
InterfaceMapping m = t.GetInterfaceMap(typeof(IDisposable));
MethodInfo mi = t.GetMethod("Dispose");
Console.WriteLine(mi == m.TargetMethods[0]); //true
因此,我假设您的类中的某些Dispose
方法具有MethodInfo
(这里是mi
,只需通过GetMethod (字符串)
)。然后你需要得到一个 InterfaceMapping Structure通过 Type.GetInterfaceMap Method 在声明类型(此处为 DisposableObject
)中实现 IDisposable
的对象.您有 TargetMethods
引用真正实现接口(interface)的方法。因此,我们只需要检查您的引用是否等于 m.TargetMethods[0]
,因为 IDisposable
只声明了一个方法。
来自 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.
请注意:如果您的类可以显式实现 IDisposable
,则 m.TargetMethods[0]
将引用显式实现。所以,我不确定除了 InterfaceMapping
之外是否有任何方法可以获取它的 MethodInfo
(参见 Use Reflection to find Methods that implement explicit interfaces)。这种情况可能容易出错。检查您的具体问题。
关于c# - 检查方法是否通过反射实现 IDisposable.Dispose,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13557092/