如何通过引用子类的实例来获取类的名称?

时间:2017-06-10 00:09:00

标签: c#

如何通过引用子类的实例来获取类的名称?

例如,

public class BaseClass
{
    public void ClassName()
    {
        // How can I get the name of the base class "BaseClass" here, without having to hardcode "BaseClass"?
        Console.WriteLine(this.GetType().Name); 
    }
}

public class SubClass: BaseClass
{
    public void ClassName()
    {
        base.ClassName();
        Console.WriteLine(this.GetType().Name);
    }
}

public static void Main(string[] args)
{
    SubClass MyObject = new SubClass();
    MyObject.ClassName();
}

输出

SubClass
SubClass

但我想要

BaseClass
SubClass

感谢。

1 个答案:

答案 0 :(得分:2)

通用方法

可能是最干净的方法:

public static class TypeHelperExtensions
{
    public static string GetTypeName<T>(this T Object)
    {
        return typeof(T).Name;
    }
}

然后:

    public class BaseClass
    {
        public virtual void ClassName()
        {
            // How can I get the name of the base class "BaseClass" here, without having to hardcode "BaseClass"?
            Console.WriteLine(this.GetTypeName()); 
        }
    }

    public class SubClass: BaseClass
    {
        public override void ClassName()
        {
            base.ClassName();
            Console.WriteLine(this.GetTypeName()); 
        }
    }

nameof()

public class BaseClass
{
    public virtual void ClassName()
    {
        // How can I get the name of the base class "BaseClass" here, without having to hardcode "BaseClass"?
        Console.WriteLine(nameof(BaseClass)); 
    }
}

public class SubClass: BaseClass
{
    public override void ClassName()
    {
        base.ClassName();
        Console.WriteLine(nameof(SubClass));
    }
}

反射

public class BaseClass
{
    public virtual void ClassName()
    {
        // If you know you will have only one parent
        var b = type.BaseType.Name
    }
}

如果您不了解结构,则可能需要执行以下操作:

    private bool _ignoreMe;

    public void ClassName()
    {
        var b = this.GetType().GetField(nameof(_ignoreMe), BindingFlags.NonPublic | BindingFlags.Instance).DeclaringType;
    }