使用反射从 'MethodInfo' Class 中读取方法的内部调用方法名称

Read a method's inner calling method names from 'MethodInfo' Class using reflection

我正在使用反射读取 class 中的所有属性和方法。所以我想使用反射来识别方法的内部调用方法。我尝试使用 'GetMethodBody()' 方法读取 MethodBody。但它仅列出局部变量。那么你能帮忙解决这个问题吗?

您无法通过反射从 MethodInfo 获取方法调用。

方法调用只是一条IL指令,从反射的角度来看都是IL。加载参数的指令和调用方法的指令没有区别。

但是,您仍然可以通过某些方式做到这一点。

  1. 您可以使用 Roslyn 检查您的方法并搜索调用节点。
  2. 你可以从MethodBody中得到IL,解析它,搜索callcallvirt指令,然后你需要解析操作数(token 在我们的例子中)并获取方法。这不是简单的方法,但您可以使用一些 ILReader 库来处理它。

更新:

有了 Roslyn,您有不止一种方法可以做到这一点。

您可以将您的方法作为 MethodDeleration 并调用 DescendantNodes().OfType<InvocationExpressionSyntax>()

您可以创建自定义 CSharpSyntaxWalker 并覆盖 VisitInvocationExpression,您也可以执行相同的操作,但使用 CSharpSyntaxRewriter

根据您的需要,您无需重写某些内容,因此您需要在 DescendantNodes(最直接的方式)和 CSharpSyntaxWalker(更优雅、更强大的方式)之间做出选择。

你在 Whosebug and all over the web. Take a look at Josh Varty series about Roslyn. Also the Github page is a good resource. Two must use tools is Quoter and TryRoslyn. Also check SyntaxVisulaizer 中有很多关于 VS 的例子。

IL 解析方式更复杂(但没那么复杂)。 正如我编写的程序那样,调用 GetILAsByteArray() 然后你需要解析字节以找到调用指令,然后获取指令操作数并解析为令牌。

对于所有这些,您可以使用一些现有的 IL Reader 例如 this or this and when you figureout the requested instructions, you need to call yourModule.ResolveMethod that return you a method base. Check here and here