如何只编写一次childs的构造函数的一部分?

时间:2018-10-13 15:48:52

标签: c# constructor abstract-class parent-child

我目前正在使用一个抽象类教室,该教室有七个不同的子类。如果我在抽象类中添加了一些东西(例如name属性),我就讨厌将其中一个孩子的构造函数的一部分粘贴到其他六个孩子的身上。

在添加必须为每个孩子设置相同/实例化的属性时,我不违反DRY原理吗?

示例:

public abstract Room
{
    // Need to be assigned in constructor.
    protected int RoomNumber { get; set; } 
    protected int PositionX { get; set; }
    protected int PositionY { get; set; }

    // Always the same at the start
    protected List<Guest> GuestsInRoom { get; set; }
    protected string ImageFilePath { get; set; }
}

public class Bedroom : Room
{
    private string Classification { get; set; }
    public Bedroom()
    {
        // Assign/instantiate all properties.
    }
}

public class Bathroom : Room
{
     private string SomeOtherProperty { get; set; }
     public Bedroom()
     {
         // Assign/instantiate all properties again
     }
 }

1 个答案:

答案 0 :(得分:2)

向基类添加一个构造函数。如果必须分配字段,请将其设置为必填参数。您可以使用修改后的Bedroom类中显示的“:base()”来调用非空父类构造函数。

public abstract Room
{
    // Need to be assigned in constructor.
    protected int RoomNumber { get; set; } 
    protected int PositionX { get; set; }
    protected int PositionY { get; set; }

    // Always the same at the start
    protected List<Guest> GuestsInRoom { get; set; }
    protected string ImageFilePath { get; set; }

    protected Room(int roomNumber, int positionX, int positionY)
    {
        RoomNumber = roomNumber;
        PositionX = positionX;
        PositionY = positionY;
        GuestsInRoom = new List<Guest>();
    }
}

public class Bedroom : Room
{
    private string Classification { get; set; }
    public Bedroom(string classification, int roomNumber, int positionX, int positionY) 
        : base(roomNumber, positionX, positionY)
    {
        // Assign/instantiate all properties.
        Classification = classification;
    }
}