在基本静态类中获取inheritance的调用者类型名称

我有:

class parent { public static string GetTypeName() { /* here i want to get the caller's type So child.GetTypeName() should display "child" */ } } class child : parent { } static void Main() { Console.WriteLine(child.GetTypeName()); } 

有可能以某种方式在基类中获取调用者的类型吗?

除非您将调用者传递给方法(作为参数)或遍历堆栈帧以获取调用者,否则这是不可能的。

当通过child类型调用parent的静态方法时,编译器将parent替换为child 。 例如,这是调用child.GetTypeName()的IL代码:

 IL_0002: call class [mscorlib]System.Type Tests.Program/parent::GetTypeName() 

我相信this.GetType()会这样做。 但此刻无法检查。

(假设你想在父方法中输入孩子的类型。)