如何在静态方法中获取当前类的名称?

问题描述:

通常我可以调用this.GetType(),但我无法在静态方法中访问它。我们如何检查它?如何在静态方法中获取当前类的名称?

+4

看:http://stackoverflow.com/questions/552629/c-sharp-print-the-class-name-from-within-a- static-function – k06a 2012-02-17 10:09:15

new StackFrame().GetMethod().DeclaringType 

MethodBase.GetCurrentMethod().DeclaringType 

new StackTrace(true).GetFrame(<frame index>).GetMethod() //e.g. <frame index> = 0 

我不知道这是否是做的最好的方式,但我通常可以设置一个private构造函数(如果我的课是static/util不可实例化的类),并且在实例上调用GetType()

private MyStaticClass 
{ 
    // ... 
} 


public static Type MyStaticMethiod() 
{ 
    return new MyStaticClass().GetType(); 
} 

使用的typeof

string className = typeof(MyClass).Name; 
+1

如果代码被粘贴到另一个类中,这个函数将不起作用 – 2012-02-17 10:47:27

+0

@lo是但重命名类保留正确的typeof语句。 – brgerner 2012-02-17 11:41:17

+1

@lo如果您通过ReSharper的* Copy Type *重构类,则typeof语句也应该保持正确。 – brgerner 2012-02-17 12:15:59