从父类调用方法并使用子类属性 [英] Call method from a parent class and use child class properties

查看:112
本文介绍了从父类调用方法并使用子类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

实际通话:

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

使用方法的父类:

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

儿童班:

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

问题:如何避免对属性名称进行硬编码,即 GetProperty("FullName").我不想对属性名称进行硬编码,而是使用其他方法并在父方法中使用它?

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?

推荐答案

首先,我建议避免使用公共字段-如果要公开状态,请使用属性.(您在自己的反射调用中询问一个属性,但是您的派生类声明了一个字段...)

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...)

到那时,您可以将 FullName 设置为基类中的 abstract 属性,并允许每个派生类按自己的意愿实现它-但您仍然可以调用它来自基类.

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.

另一方面,如果每个派生类都必须实现它,为什么不将其传递给基类的构造函数呢?该类在没有 FullName 的情况下还是有意义的-否则-如果没有 FullName 字段,则当前代码将中断.为什么不从基类开始呢?

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?

这篇关于从父类调用方法并使用子类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆