简体   繁体   中英

Accessing derived class property members from base class object in CSharp

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
    }

}

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM