如果我有一个名为MyProgram的类,是否有一种方法检索“MyProgram”作为字符串?


当前回答

试试这个:

this.GetType().Name

其他回答

作为参考,如果您有从另一个类型继承的类型,您也可以使用

this.GetType().BaseType.Name

试试这个:

this.GetType().Name

这个可以省略。所有你需要得到当前类名的是:

GetType().Name

这可以用于泛型类

typeof (T)。的名字

使用这个

假设应用程序Test.exe正在运行,函数是form1中的foo()[基本上是类form1],然后上面的代码将生成下面的响应。

string s1 = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;

这将返回。

s1 = "TEST.form1"

函数名:

string s1 = System.Reflection.MethodBase.GetCurrentMethod().Name;

将返回

s1 = foo 

注意,如果你想在异常使用中使用这个:

catch (Exception ex)
{

    MessageBox.Show(ex.StackTrace );

}