7

System.Reflection.Type包含GetInterfaceMap,它有助于确定哪些方法从接口实现某些方法。

Mono.Cecil是否包含这样的内容?或者如何实现这种行为?

4

1 回答 1

7

不,Cecil 不提供这种方法,因为 Cecil 只为我们提供 CIL 元数据。(有项目 Cecil.Rocks,其中包含一些有用的扩展方法,但没有这个)

在 MSIL 方法中有一个属性“覆盖”,它包含对该方法覆盖的方法的引用(在 Cecil 中,MethodDefinition 类中确实有一个属性 Overrides)。但是,该属性仅在某些特殊情况下使用,例如显式接口实现。通常这个属性是空的,哪些方法被所讨论的方法覆盖是基于约定的。这些约定在 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...
于 2011-04-27T16:32:33.940 回答