Extend object with values ​​from parent

Let's say I have a class:

public class Parent
{
    public string Name { get; set; }
    public string City { get; set; }
}

and in some function I get a list of objects of type "Parent", the next I would like to expand these objects with a new field with some value, so I declare an extended class as follows:

public class Child : Parent
{
    public Child(Parent parent)
    {
        Name = parent.Name;
        City = parent.City;
    }
    public int Age { get; set; }
}

and call the cost constructor for each extended object. Is there a better way to do this? What if there are several properties in the parent? Maybe there is an even more elegant way to achieve this?

+3
source share
3 answers

I think maybe you are looking for a constructor template. Each level defines a constructor protectedthat copies the corresponding properties:

public class Parent
{
    public string Name { get; set; }
    public string City { get; set; }

    //normal constructor
    public Parent()
    {

    }

    protected Parent(Parent copy)
    {
        this.Name = copy.Name;
        this.City = copy.City;
    }
}

Child Parent, -, :

public class Child : Parent
{
    public string NewInfo { get; set; }

    public Child(Parent copy)
        : base(copy)
    {

    }
}

:

Parent parent = new Parent() { Name = "Name", City = "StackOverflow"};

Child child = new Child(parent) { NewInfo = "Something new!" };

Console.WriteLine(child.Name); //Name
Console.WriteLine(child.City); //StackOverflow
Console.WriteLine(child.NewInfo); //Something new!

, , .

EDIT: :

- , , , .

, :

public class Child
{
    private readonly Parent WrappedParent;

    public string NewInfo { get; set; }

    public string Name 
    { 
        get { return WrappedParent.Name; }
        set { WrappedParent.Name = value; }
    }

    public string City 
    { 
        get { return WrappedParent.City; }
        set { WrappedParent.City = value; }
    }

    public Child(Parent wrappedParent)
    {
        this.WrappedParent = wrappedParent; 
    }
}

- , ( a) "Parent", " " . "" IParent, , - "" , IParent .

+3

, ,

public class Parent
{
    public Parent(string name, string city)
    {
       Name = name;
       City = city;
    }

    public string Name { get; set; }
    public string City { get; set; }
}

public class Child : Parent
{
    public Child(string name, string city, int age) : base(name, city)
    {
       Age = age;
    }
    public int Age { get; set; }
} 
+2

You can do it

public class Parent
{
    public string Name { get; set; }
    public string City { get; set; }

    public Parent(string name, string city)
    {
        this.Name = name;
        this.City = city;
    }

    public Parent():this(string.Empty, string.Empty)
    {
    }
}

public class Child : Parent
{
    public Child(Parent parent, int age):base(parent.Name, parent.City)
    {
        this.Age = age;
    }

    public int Age { get; set; }
}
0
source

All Articles