我们可以使用基类对象访问派生类的属性吗? [英] Can we access derived class properties by using base class object?

查看:223
本文介绍了我们可以使用基类对象访问派生类的属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用基类对象访问派生类的属性吗?

Can we access derived class properties by using base class object?

我有一个基础课

 public abstract class FnmaRecord
    {
        public int Id { get; set; }            
        public abstract String Prefix
        {
            get;
        }
    }

并且有许多派生类继承了FnmaRecord类

And there are many derived classes which inherits the FnmaRecord class

 public class TransactionHeader : FnmaRecord
    {
        public override string Prefix { get {return "TH";} }

        public static readonly string TransactionId = "T100099-002";

        public String TransactionControlNumber { get; set; }

    }


public class TitleHolder : FnmaRecord
    {
        public override string Prefix { get {return "02C";} }

        public string TitleHolderName { get; set; }
    }

现在我可以在另一个类中使用FnmaRecord的实例来访问TitleHolder中的属性吗?

Now can i use the instance of the FnmaRecord in another class to access the property in TitleHolder?

推荐答案

否.正如FredrikMörk在中指出的那样在这里回答:

No. As Fredrik Mörk states in their answer here:

基类不知道(更重要的是不知道) 关于派生类的属性.不同的派生类可能具有不同的一组 添加的属性.使基类意识到这一点将抵消 面向对象设计的重要原理

Base class does not (and more importantly should not) know anything about derived class properties. Different derived classes could have a different set of added properties. Making the base class aware of this would counteract important principles of object oriented design

这篇关于我们可以使用基类对象访问派生类的属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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