C#反射-我可以检查一种方法是否调用另一种方法

Eig*_*ite 3 c# reflection

我正在寻找一种确保方法“ A”调用方法“ B”的方法。大致来说,这笔交易是..

class one
{
    internal static void MethodA()
    {
        //Do Something here.  SHOULD be calling B.
    }

    void MethodB()
    {
         //MUST be called by MethodA.
    }
}

class two
{
    internal void MethodA()
    {
        //Test that MethodA calls MethodB
    }
}
Run Code Online (Sandbox Code Playgroud)

我应该指出,我为此坚持使用.Net 2.0,因此ExpressionTrees是不可行的。我什至不确定他们会帮忙,但这是我最初的想法。

编辑:这是一个内部工具,用于可视化源代码的循环复杂性,因此我不关心在这里破坏封装。此外,..很可能仅使用System.Reflection就必须完成此操作。

pli*_*nth 5

在许多情况下,这是可行的,但是您将需要进行一些输入。你要做的第一件事就是使用ILReader类-有一个轮廓一个在这里(和在一个弗洛里安Doyon发布)。然后,您要将其包装在这样的类中:

public class MethodCalls : IEnumerable<MethodInfo>
{
    MethodBase _method;

    public MethodCalls(MethodBase method)
    {
        _method = method;
    }

    public IEnumerator<MethodInfo> GetEnumerator()
    {
        // see here: http://blogs.msdn.com/haibo_luo/archive/2005/10/04/476242.aspx
        ILReader reader = new ILReader(_method);

        foreach (ILInstruction instruction in reader) {
            CallInstruction call = instruction as CallInstruction;
            CallVirtInstruction callvirt = instruction as CallVirstInstruction;
            if (call != null)
            {
                yield return ToMethodInfo(call);
            }
            else if (callvirt != null)
            {
                yield return ToMethodInfo(callvirt);
            }
        }
    }
}

MethodInfo ToMethodInfo(CallInstruction instr) { /* ... */ }

MethodInfo ToMethodInfo(CallVirtInstruction instr) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)

ToMethodInfo的两种形式都未定义,因为CallInstruction也未定义。尽管如此,该大纲有望将您的问题变成:

public static bool Calls(MethodBase caller, MethodInfo callee)
{
    return new MethodCalls(caller).Contains(callee);
}
Run Code Online (Sandbox Code Playgroud)