使用反射查找方法的所有引用 [英] Find All References of a Method Using Reflection

查看:108
本文介绍了使用反射查找方法的所有引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我想在运行时找到单个类的所有方法调用的位置。我正在使用反射,但我找不到一种方法来确定它的使用位置。例如:



Hi,

I want to find the location of all method calls to a single class at runtime. I'm using reflection, but I cannot find a way to locate where it is being used. For example:

public class Test 
{
   public void Method1()
   { 
     // do something 
   }
   public void Method2()
   {
     Method2();
   }
}





我想在运行时找到Method2由Method1调用。有办法吗?



我认为应该有,因为Visual Studio可以通过Find All References来实现。谢谢。



I want to find at runtime Method2 is called by Method1. Is there a way?

I think there should be, as Visual Studio can do it via "Find All References". Thanks.

推荐答案

我想你需要解析你正在查看的方法的方法体,参见这个 [ ^ ]。它可能会帮助你开始。



顺便说一句,如果你在Visual Studio宏中这样做,我相信VS提供了一些可能有用的对象这没有IL解析。
I would imagine you'd need to parse the method body of the methods you're looking at, see this[^]. It might help you get started.

Btw, if you're doing this within a Visual Studio macro, I believe VS provides some objects that might be of use to doing this without IL parsing.


我不确定这是不是你想要的。但也许这会对你有所帮助: -



测试课:



I am not sure if this is exactly what you want. But may be this will help you: -

A test class:

public class TestClass
{
    public void Test()
    {
        Console.WriteLine("Test");
        Console.Write(10);
        DateTime date = DateTime.Now;
        Console.WriteLine(date);
    }
}







打印所有方法的另一个代码TextClass.Test()






Another code to print all the methods used within TextClass.Test()

MethodBase methodBase = typeof(TestClass).GetMethod("Test");
var instructions = MethodBodyReader.GetInstructions(methodBase);

foreach (Instruction instruction in instructions)
{
    MethodInfo methodInfo = instruction.Operand as MethodInfo;

    if(methodInfo != null)
    {
        Type type = methodInfo.DeclaringType;
        ParameterInfo[] parameters = methodInfo.GetParameters();

        Console.WriteLine("{0}.{1}({2});",
            type.FullName,
            methodInfo.Name,
            String.Join(", ", parameters.Select(p => p.ParameterType.FullName + " " + p.Name).ToArray())
        );
    }
}





输出结果为:





The output was:

System.Console.WriteLine(System.String value);
System.Console.Write(System.Int32 value);
System.DateTime.get_Now();
System.Console.WriteLine(System.Object value);





希望这会有所帮助。让我知道这是否对你有所帮助。



-

AJ



Hope this helps. Let me know if or not this helped you.

--
AJ


这篇关于使用反射查找方法的所有引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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