代码之家  ›  专栏  ›  技术社区  ›  Kevin Le - Khnle

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

  •  5
  • Kevin Le - Khnle  · 技术社区  · 15 年前

    在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 回复  |  直到 15 年前
        1
  •  6
  •   this. __curious_geek    15 年前
    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(),并将获得该类型的元信息。

    你也可以这样做,

    public class Base
    {
    
    }
    
    public class Subclass : Base
    {
    
    }
    
    //In your client-code
    Subclass subclass = new Subclass();
    string className = subclass.GetType().Name;
    

    编辑

    此外,如果在任何情况下确实需要定义getClassName(),我强烈建议将其作为属性[根据.NET Framework设计指南行],因为getClassName()的行为不是动态的,并且每次调用它时都会返回相同的值。

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

    编辑2

    优化后的版本阅读评论克里斯。

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