使用C#反射查找声明函数的接口

我正在寻找一种简单的方法来获取有关方法的反射信息,该方法从类开始一直返回到声明接口。这是简化的代码:


public interface Ix

{

    void Function();

}

public class X : Ix

{

    public void Function() {}

}


public class Y : X

{

}

类X的方法信息不包含有关在Ix接口中声明Function的信息。这里是电话:


var info = typeof(X).GetMethod("Function");

var baseInfo = info.GetBaseDefinition()

它返回以下数据:


info.DeclaringType --> MyNamespace.X

info.ReflectedType --> MyNamespace.X

baseInfo.DeclaringType --> MyNamespace.X

baseInfo.ReflectedType --> MyNamespace.X

对于类Y,返回相同的信息。


我如何才能确定在接口Ix中声明了此函数,而无需遍历所有已实现的接口和类X或Y的基类?我可能会错过一些简单的东西,但我无法弄清楚是什么。这可能是错误吗?


这是.Net Core SDK版本2.1.104和Visual Studio 2017


一只名叫tom的猫
浏览 183回答 2
2回答

米琪卡哇伊

您似乎想要对可以从GetInterfaceMap获得的信息进行反向查找。构建它非常简单,public static Dictionary<MethodInfo, List<(Type, MethodInfo)>> GetReverseInterfaceMap(Type t){&nbsp; &nbsp; var reverseMap = new Dictionary<MethodInfo, List<(Type, MethodInfo)>>();&nbsp; &nbsp; var maps = t.GetInterfaces().ToDictionary(i => i, i => t.GetInterfaceMap(i));&nbsp; &nbsp; foreach (var m in t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var list = new List<(Type, MethodInfo)>();&nbsp; &nbsp; &nbsp; &nbsp; foreach (var (i, map) in maps)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int index = 0; index < map.TargetMethods.Length; index++)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var targetMethod = map.TargetMethods[index];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (targetMethod == m)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; list.Add((map.InterfaceType, map.InterfaceMethods[index]));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; reverseMap[m] = list;&nbsp; &nbsp; }&nbsp; &nbsp; return reverseMap;}关于界面的工作方式,有几点要说明,因为画面并不像“派生”->“基础”->“界面”那样简单。有一个映射描述了每个接口方法调用的具体方法。该信息很容易获得,因为运行时需要它来实现接口调度。然而,相反的过程并不那么简单。一种具体方法可能是多个接口的映射。接口方法也可能被派生类重新映射。这一切都需要考虑在内。
打开App,查看更多内容
随时随地看视频慕课网APP