如何获得的使用反射在C#中从一个方法调用的方法列表 [英] How to get the list of methods called from a method using reflection in C#

查看:750
本文介绍了如何获得的使用反射在C#中从一个方法调用的方法列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得我可以检查是否方法1是从方法2使用反射叫什么名字?

How to get the list of methods called from a method using reflection in C# (DotNet) or How can I check whether Method1 is called from Method2 using reflection?

推荐答案

正如其他人所指出的那样,这是基本上是不可能使用反射的事情。你必须分析的方法自己IL字节码,以便找到呼叫。幸运的是,有一个美丽的项目由单塞西尔(也的的NuGet )。这里有一个小例子来说明如何你的问题可以用单塞西尔解决:

As others have pointed out, this is essentially impossible to do using reflection. You'd have to parse the IL byte code of the methods yourself in order to find the calls. Luckily, there's a beautiful project going by the name of Mono Cecil (also available on nuget) that does all the hard work for you. Here's a minimal example to illustrate how your problem could be solved using Mono Cecil:

static class MethodDefinitionExtensions
{
    public static bool CallsMethod(this MethodDefinition caller, 
        MethodDefinition callee)
    {
        return caller.Body.Instructions.Any(x => 
            x.OpCode == OpCodes.Call && x.Operand == callee);
    }
}

class Program
{
    private static AssemblyDefinition _assembly = AssemblyDefinition.ReadAssembly(
        System.Reflection.Assembly.GetExecutingAssembly().Location);

    private static void Method1()
    {
        Method2();
    }

    private static void Method2()
    {
        Method1();
        Method3();
    }

    private static void Method3()
    {
        Method1();
    }

    private static IEnumerable<MethodDefinition> GetMethodsCalled(
        MethodDefinition caller)
    {
        return caller.Body.Instructions
            .Where(x => x.OpCode == OpCodes.Call)
            .Select(x => (MethodDefinition)x.Operand);
    }

    private static MethodDefinition GetMethod(string name)
    {
        TypeDefinition programType = _assembly.MainModule.Types
            .FirstOrDefault(x => x.Name == "Program");
        return programType.Methods.First(x => x.Name == name);
    }

    public static void Main(string[] args)
    {
        MethodDefinition method1 = GetMethod("Method1");
        MethodDefinition method2 = GetMethod("Method2");
        MethodDefinition method3 = GetMethod("Method3");

        Debug.Assert(method1.CallsMethod(method3) == false);
        Debug.Assert(method1.CallsMethod(method2) == true);
        Debug.Assert(method3.CallsMethod(method1) == true);

        Debug.Assert(GetMethodsCalled(method2).SequenceEqual(
            new List<MethodDefinition> { method1, method3 }));
    }
}

这篇关于如何获得的使用反射在C#中从一个方法调用的方法列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆