gpt4 book ai didi

c# - Mono.Cecil 类似于 Type.GetInterfaceMap 吗?

转载 作者:太空狗 更新时间:2023-10-29 21:30:31 25 4
gpt4 key购买 nike

System.Reflection.Type 包含 GetInterfaceMap这有助于确定什么方法从接口(interface)实现某些方法。

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

最佳答案

不,Cecil 不提供这样的方法,因为 Cecil 只按原样为我们提供 CIL 元数据。 (有项目Cecil.Rocks,里面有一些有用的扩展方法,但不是这个)

在 MSIL 中,方法有一个属性“overrides”,它包含对该方法覆盖的方法的引用(在 Cecil 中,MethodDefinition 类中确实有一个属性 Overrides)。但是,该属性仅在某些特殊情况下使用,例如显式接口(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com