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

时间:2022-07-03 23:43:50

This question already has an answer here:

这个问题在这里已有答案:

Normally I can call this.GetType(), but I can't access this in a static method. How can we check it?

通常我可以调用this.GetType(),但我无法在静态方法中访问它。我们怎么检查呢?

3 个解决方案

#1


28  

new StackFrame().GetMethod().DeclaringType

or

要么

MethodBase.GetCurrentMethod().DeclaringType

or

要么

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

#2


13  

Use typeof:

使用typeof:

string className = typeof(MyClass).Name;

#3


0  

I don't know if it's the best way to do it, but I usually set a private constructor (if my class is a static/util non-instantiable class) and than call GetType() on an instance.

我不知道这是否是最好的方法,但我通常设置一个私有构造函数(如果我的类是一个static / util非实例化类),而不是在一个实例上调用GetType()。

private MyStaticClass
{
    // ...
}


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

#1


28  

new StackFrame().GetMethod().DeclaringType

or

要么

MethodBase.GetCurrentMethod().DeclaringType

or

要么

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

#2


13  

Use typeof:

使用typeof:

string className = typeof(MyClass).Name;

#3


0  

I don't know if it's the best way to do it, but I usually set a private constructor (if my class is a static/util non-instantiable class) and than call GetType() on an instance.

我不知道这是否是最好的方法,但我通常设置一个私有构造函数(如果我的类是一个static / util非实例化类),而不是在一个实例上调用GetType()。

private MyStaticClass
{
    // ...
}


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