这是一个很好地利用继承的例子吗?

时间:2013-03-12 14:52:52

标签: c# inheritance

我一直在读,继承通常是糟糕的代码设计。尽管如此,我有时会继承业务对象的List或BindingList。这是我可能使用的简单业务对象:

public class RowType
{
    public string Name { get; set; }
    public double Sales { get; set; }
}

以下是包含RowType s集合的对象的两个选项:

//Option A: "Has-A" relationship
public class RowHolderType
{
    private readonly BindingList<RowType> _rows;
    public BindingList<RowType> Rows { get { return this._rows; } }
    public RowHolderType() { this._rows = new BindingList<RowType>(); }
}

//Option B: "Is-A" relationship
public class RowHolderType : BindingList<RowType>
{
    public RowHolderType() : base() { }
    public RowHolderType(IList<RowType> list) : base(list) { }
}

我通常使用选项B.我发现在使用选项B时我通常需要编写更少的代码。我通常使用这样的类在WPF窗口中显示可编辑数据列表。

使用选项B有一些隐藏的缺点吗​​?或者我可以继续愉快地延长BindingList<T> s?

编辑:添加示例。

我在评论中提到,当我希望更好地控制BindingList可以发送的通知时,我可能会使用选项B.我可能想表明我正在开始一批更新,然后完成同一批更新。为此,我将继承BindingList并添加一些功能:

public class RowTypeHolder : BindingList<RowType>
{
    public event BeforeListChangedEventHandler BeforeListChanged;
    public delegate void BeforeListChangedEventHandler(RowTypeHolder sender, RowTypeHolderEventArgs e);

    public event AfterListChangedEventHandler AfterListChanged;
    public delegate void AfterListChangedEventHandler(RowTypeHolder sender, RowTypeHolderEventArgs e);

    public void OnBeforeListChanged(RowTypeHolderEventArgs.ChangeType change, string eventName)
    {
        if (this.BeforeListChanged != null)
            this.BeforeListChanged(this, new RowTypeHolderEventArgs(change, 0, eventName));
    }

    public void OnAfterListChanged(RowTypeHolderEventArgs.ChangeType change, int numChanges, string eventName)
    {
        if (this.AfterListChanged != null)
            this.AfterListChanged(this, new RowTypeHolderEventArgs(change, numChanges, eventName));
    }
}

来电者负责发送BeforeListChangedAfterListChanged次通知。我没有尝试使用“Has-A”类型的关系,但我认为该代码会更加丑陋。 (请注意,我遗漏了RowTypeHolderEventArgsRowTypeHolderEventArgs.ChangeType的定义。我不认为这个例子很重要。)

1 个答案:

答案 0 :(得分:0)

如果没有更多的上下文,我很难决定哪一个更喜欢,我通常喜欢在我的问题心理模型之后构建代码。

问自己这个问题:

修辞意义上的

RowHolderType一个BindingList<RowType>?如果是,那么继承是100%合适的。