从CSharp中的基类对象访问派生类属性成员 [英] Accessing derived class property members from base class object in CSharp

查看:270
本文介绍了从CSharp中的基类对象访问派生类属性成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用基类对象访问派生类的属性成员。

I am having trouble accessing property members of derived class using base class object.

场景:

public class BaseClass{
    public virtual Write(BaseClass data){
    }
}

public class DerivedClass : BaseClass{

    private string name:

    public string Name {get {return name} set {name = value;} }

    public override Write(BaseClass data){
     Console.println(data.Name);  // gives me error here
    }

}


推荐答案

在访问派生类中访问属性时遇到问题的原因是基类没有(更重要的是不应该)知道它们的任何内容。不同的派生类可以具有不同的添加属性集。让基类意识到这一点会抵消面向对象设计的重要原则。想到的一个原则是 Liskov替代原则

The reason you have a problem accessing properties in derived classes is that the base class does not (and more importantly should not) know anything about them. 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. One such principle that comes to mind is the Liskov Substitution Principle.

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

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