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

klm*_*lm_ 3 .net c# 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());
}
Run Code Online (Sandbox Code Playgroud)

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

Jef*_*nal 9

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

编译器的替代品parent用于child打电话时parent通过的静态方法child的类型.例如,这是调用以下内容的IL代码child.GetTypeName():

IL_0002:  call   class [mscorlib]System.Type Tests.Program/parent::GetTypeName()
Run Code Online (Sandbox Code Playgroud)