在基类中定义一个返回其自身名称的方法(使用反射) - 子类继承此行为

时间:2010-06-17 06:17:41

标签: c# reflection

在C#中,使用反射,是否可以在基类中定义返回自己名称的方法(以字符串的形式)并让子类以多态方式继承此行为?

例如:

public class Base
{
    public string getClassName()
    {
        //using reflection, but I don't want to have to type the word "Base" here.
        //in other words, DO NOT WANT  get { return typeof(Base).FullName; }
        return className; //which is the string "Base"
    }
}

public class Subclass : Base
{
    //inherits getClassName(), do not want to override
}

Subclass subclass = new Subclass();
string className = subclass.getClassName(); //className should be assigned "Subclass"  

1 个答案:

答案 0 :(得分:6)

public class Base
{
    public string getClassName()
    {
        return this.GetType().Name;
    }
}

实际上,you don't need to create a method getClassName() just to get the type-name。您可以在任何.Net对象上调用GetType(),您将获得Type的元信息。

您也可以这样做,

public class Base
{

}

public class Subclass : Base
{

}

//In your client-code
Subclass subclass = new Subclass();
string className = subclass.GetType().Name;

修改

此外,如果你真的需要在任何情况下定义getClassName(),我强烈建议将它作为一个属性[根据.net框架设计指南行],因为getClassName()的行为不是动态的,每次调用它时,它总会返回相同的值。

public class Base
{
    public string ClassName
    {
        get
        {
            return this.GetType().Name;
        }
    }
}

EDIT2

优化版本阅读Chris的评论后。

public class Base
{
    private string className;
    public string ClassName
    {
        get
        {
            if(string.IsNullOrEmpty(className))
                className = this.GetType().Name;
            return className;
        }
    }
}