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


当前回答

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

this.GetType().BaseType.Name

其他回答

试试这个:

this.GetType().Name

我还想把这个吐出来。我认为@micahtan的发帖方式更可取。

typeof(MyProgram).Name

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

nameof(MyProgram)

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

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();
    }
}

获取Asp.net的当前类名

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