日期:2014-05-17 浏览次数:21076 次
class A
{
    public C c = new C();
    public void CallM1Method()
    {
        c.M1();
    }
}
class B
{
    public C c = new C();
    public void CallM1Method()
    {
        c.M1();
    }
}
class C
{
    public void M1()
    {
        // 获取到底是 A 调用的还是 B 调用的
        Type aType = typeof(A);
        Type bType = typeof(B);
        StackTrace trace = new StackTrace();
        StackFrame[] frames = trace.GetFrames();
        foreach (StackFrame frame in frames)
        {
            Type t = frame.GetMethod().DeclaringType;
            if (t == aType)
            {
                Console.WriteLine("A invoke");
                break;
            }
            if (t == bType)
            {
                Console.WriteLine("B invoke");
                break;
            }
        }
    }
}