如何在静态方法中获取当前类的名称?
通常我可以调用this.GetType(),但我无法在静态方法中访问它。 我们怎么检查呢?
new StackFrame().GetMethod().DeclaringType
要么
MethodBase.GetCurrentMethod().DeclaringType
要么
new StackTrace(true).GetFrame().GetMethod() //eg = 0
使用typeof :
string className = typeof(MyClass).Name;
我不知道这是否是最好的方法,但我通常设置一个private
构造函数(如果我的类是一个static / util非实例化类),而不是在一个实例上调用GetType()
。
private MyStaticClass { // ... } public static Type MyStaticMethiod() { return new MyStaticClass().GetType(); }