Accessing derived class property members from base class object in CSharp

非 Y 不嫁゛ 提交于 2019-12-29 09:32:20

问题


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

Scenario:

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
    }

}

回答1:


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.




回答2:


As stated, name does not exists in the BaseClass.

Either move "name" to the base class or create a separate Write Method that writes the inherited class's specific data.

public class DerivedClass : BaseClass{

    public string Name { get; set; }

    public override void Write(DerivedClass data) {
        Console.printLn(data.Name);
        base.Write(data)
    }

    // why print a different instance, just write self
    public void Write() {
        Console.printLn(this.Name);
        base.Write(this)
    }

}

Not sure why the Class would accept a different Class Instance to write when you can just invoke write on itself. Change the BaseClass signture to

public virtual Write()

or like WebControls

public virtual Write(HtmlTextWriter writer);

if you want simply debugging, you could just serialize to JSON or XML and then output that to your console



来源:https://stackoverflow.com/questions/4329276/accessing-derived-class-property-members-from-base-class-object-in-csharp

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