System.Reflection.Type 包含GetInterfaceMap,它有助于确定哪种方法从接口(interface)实现某种方法。
Mono.Cecil 是否包含类似这样的内容?
还是如何实现这种行为?
最佳答案
否,Cecil不提供这种方法,因为Cecil仅按原样提供给我们CIL元数据。 (有一个Cecil.Rocks项目,其中包含一些有用的扩展方法,但不包括这一方法)
在MSIL中,方法具有“覆盖”属性,该属性包含对该方法覆盖的方法的引用(在Cecil中,MethodDefinition类中确实存在属性“覆盖”)。但是,此属性仅在某些特殊情况下使用,例如显式接口(interface)实现。通常,此属性保留为空,并且所讨论的方法将基于约定重写哪些方法。这些约定在ECMA CIL标准中进行了描述。简而言之,方法将覆盖具有相同名称和签名的方法。
以下代码段可能对您和本讨论都有帮助:http://groups.google.com/group/mono-cecil/browse_thread/thread/b3c04f25c2b5bb4f/c9577543ae8bc40a
public static bool Overrides(this MethodDefinition method, MethodReference overridden)
{
Contract.Requires(method != null);
Contract.Requires(overridden != null);
bool explicitIfaceImplementation = method.Overrides.Any(overrides => overrides.IsEqual(overridden));
if (explicitIfaceImplementation)
{
return true;
}
if (IsImplicitInterfaceImplementation(method, overridden))
{
return true;
}
// new slot method cannot override any base classes' method by convention:
if (method.IsNewSlot)
{
return false;
}
// check base-type overrides using Cecil's helper method GetOriginalBaseMethod()
return method.GetOriginalBaseMethod().IsEqual(overridden);
}
/// <summary>
/// Implicit interface implementations are based only on method's name and signature equivalence.
/// </summary>
private static bool IsImplicitInterfaceImplementation(MethodDefinition method, MethodReference overridden)
{
// check that the 'overridden' method is iface method and the iface is implemented by method.DeclaringType
if (overridden.DeclaringType.SafeResolve().IsInterface == false ||
method.DeclaringType.Interfaces.None(i => i.IsEqual(overridden.DeclaringType)))
{
return false;
}
// check whether the type contains some other explicit implementation of the method
if (method.DeclaringType.Methods.SelectMany(m => m.Overrides).Any(m => m.IsEqual(overridden)))
{
// explicit implementation -> no implicit implementation possible
return false;
}
// now it is enough to just match the signatures and names:
return method.Name == overridden.Name && method.SignatureMatches(overridden);
}
static bool IsEqual(this MethodReference method1, MethodReference method2)
{
return method1.Name == method2.Name && method1.DeclaringType.IsEqual(method2.DeclaringType);
}
// IsEqual for TypeReference is similar...
关于c# - Mono.Cecil之类的Type.GetInterfaceMap吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4917509/