Get the name of the caller’s inherited name in the base static class

I have:

class parent
{
    public static string GetTypeName()
    { 
        /* here i want to get the caller type
        So child.GetTypeName() should display "child" */
    }            
}     

class child : parent { }

static void Main()
{
    Console.WriteLine(child.GetTypeName());
}

Is it possible to somehow get the type of caller in the base class?

+3
source share
2 answers

This is not possible if you do not pass the caller to the method (as an argument) or go through the stack stack to get the caller.

The compiler replaces parentwith childwhen invoking static methods parentusing a type child. For example, here is the IL code to call child.GetTypeName():

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

I believe I this.GetType()will do it. But I can’t check at the moment.

(assuming you want the child type to be in the parent method.)

0

Source: https://habr.com/ru/post/1786414/


All Articles