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


当前回答

获取Asp.net的当前类名

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

其他回答

试试这个:

this.GetType().Name

如果你在派生类中需要这个,你可以把这个代码放在基类中:

protected string GetThisClassName() { return this.GetType().Name; }

然后,您可以在派生类中找到该名称。返回派生类名。当然,当使用新的关键字“nameof”时,就不需要这样的变化行为了。

此外,你可以这样定义:

public static class Extension
{
    public static string NameOf(this object o)
    {
        return o.GetType().Name;
    }
}

然后像这样使用:

public class MyProgram
{
    string thisClassName;

    public MyProgram()
    {
        this.thisClassName = this.NameOf();
    }
}

在c# 6.0中,你可以使用操作符的名称:

nameof(MyProgram)

获取Asp.net的当前类名

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

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

GetType().Name