110,538
社区成员
发帖
与我相关
我的任务
分享
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;
}
}
}
}