比如有方法A,当B方法调用A时,怎么才能在A里知道是B在调用?

解决方案 »

  1.   

    在B里可以通过反射,在堆栈里查找
    System.Reflection.MethodInfo mi = (System.Reflection.MethodInfo) (new StackTrace().GetFrame(1).GetMethod());
    if(mi.Name=="A")
      //A调用的
      

  2.   


    如果这个方法被CLR内联,未必能得到正确的结果。
    要不然Windows事件也不要什么sender参数了。在.NET 4.5/VS2012以前,这个问题无解。在.NET 4.5上,有一组专门的Attribute可以把调用信息嵌入方法。
      

  3.   


    学习,请问什么叫CLR内联? 之前只知道在堆栈里可以查找,现在又学习了一种方法
      

  4.   

    WhoCalledMe
      

  5.   

    static void A()
            {
                StackFrame sf = new StackTrace().GetFrame(1);
                Console.WriteLine(sf.GetMethod().Name);
            }
      

  6.   

    比如说
    Main()
    {
        int i = add(1, 2);
    }
    int add(int a, int b)
    {
        return a + b;
    }
    如果CLR翻译成:
    Main()
    {
        push 1
        push 2
        call add
        move i, a
    }
    这个是正常的
    为了性能的考虑,CLR,也可能编译成
    Main()
    {
        move i, 1
        add i, 2
    }
    也就是把子函数嵌入到主程序中,取消了调用,这个就叫“内联”。
      

  7.   

    +1 以前封装日志输出的方法,用过MethodInfo.调用的完整命名空间,方法都可以获取到,