Get derived type from static method

I want to get a derived type from a static method.

I want to do something like this

void foo() { this.getType(); } 

but in the static method

I know that

 MethodBase.GetCurrentMethod().DeclaringType 

returns the base type, but I need to get.

+4
source share
2 answers

Assuming you mean that you have something like this

 class MyBaseClass { public static void DoSomething() { Console.WriteLine(/* current class name */); } } class MyDerivedClass : MyBaseClass { } 

and want MyDerivedClass.DoSomething(); print "MyDerivedClass" , then the answer will be as follows:

No problem with your problem. Static methods are not inherited as instance methods. You can access DoSomething using MyBaseClass.DoSomething or MyDerivedClass.DoSomething , but both are compiled as calls to MyBaseClass.DoSomething . It is impossible to find out what was used in the source code to make the call.

+9
source

I think you need something like this script:

 void Main() { Base.StaticMethod(); // should return "Base" Derived.StaticMethod(); // should return "Derived" } class Base { public static void StaticMethod() { Console.WriteLine(MethodBase.GetCurrentMethod().DeclaringType.Name); } } class Derived: Base { } 

This code, however, will return

 Base Base 

This is because the call to the static method is allowed at compile time as a call to the base class, which actually defines it, even if it was called from a derived class. Lines

 Base.StaticMethod(); Derived.StaticMethod(); 

generates the following IL:

 IL_0001: call Base.StaticMethod IL_0006: nop IL_0007: call Base.StaticMethod 

In a word, this is impossible.

+6
source

All Articles