C # any way to access a class name of a static class through code?

In a static class, you cannot use the keyword "this", so I cannot call this.GetType().GetFullName if I have

 public static class My.Library.Class { public static string GetName() { } } 

Is there anything I can call from GetName that will return My.Library.Class

+4
source share
3 answers

you can get the type of a predefined class with:

 typeof(My.Library.Class).FullName 

If you need a "class declaring this method", you will need to use

 MethodBase.GetCurrentMethod().DeclaringType.FullName 

However, there is a chance that this method will be built in by the compiler . You can switch this call to the static constructor / initializer of the class (which will never be inlined - log4net recommends this approach):

 namespace My.Library public static class Class { static string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; public static string GetName() { return className; } } } 

Using [MethodImpl(MethodImplOptions.NoInlining)] may help, but you really should read if you are considering it

HTH - Rob

+4
source
 typeof(My.Library.Class).FullName 
+1
source
 MethodBase.GetCurrentMethod().DeclaringType.FullName 
+1
source

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


All Articles