Call method from a parent class and use child class properties

只谈情不闲聊 提交于 2020-01-07 05:10:08

问题


Actual call:

ChildClass classCall=new ChildClass();
classCall.FullName="test name";
string returnName=classCall.GetName();

Parent class with method:

public class BaseClass
{
    public string GetName()
    {
        // I can request the value of the property like this.
        return this.GetType().GetProperty("FullName")
                   .GetValue(this, null).ToString();
    }
}

Child class:

public partial class ChildClass : BaseClass
{
    public string FullName;
    public int Marks;
}

Question: How can I avoid hardcoding the property name, i.e. GetProperty("FullName"). I don't want to hardcode the property name, rather use some other approach and use it in parent method?


回答1:


Firstly, I'd suggest avoiding using public fields - use properties if you want to make state public. (You're asking for a property in your reflection call, but your derived class declares a field...)

At that point, you can make FullName an abstract property in the base class, and allow each derived class to implement it however they want - but you can still call it from the base class.

On the other hand, if every derived class is going to have to implement it, why not just pass it into the base class's constructor? Either the class makes sense without a FullName or it doesn't - your current code will break if there isn't a FullName field, so why not have it in the base class to start with?




回答2:


    public class BaseClass
    {
        public virtual string GetName()
        {
            return string.Empty;
        }
    }

    public partial class ChildClass : BaseClass
    {

        public string FullName;
        public int Marks;

        public override string GetName()
        {
            return FullName;
        }
    }

However, if you never want to initialize a BaseClass object you want to make it abstract and force everybody who implements it to implement its own version of the GetName method:

    public abstract class BaseClass
    {
        public abstract string GetName();
    }

BR



来源:https://stackoverflow.com/questions/27023200/call-method-from-a-parent-class-and-use-child-class-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!