为什么不应该让类继承 List<T>?
大家好!我是一名 C# 初学者,遇到了设计问题。我正在编写一个图书馆管理应用程序。我有一个 `Book` 类,我想创建一个 `Library` 类,它包含书籍列表,并且有自己的方法,例如 `FindByAuthor()` 或 `GetTotalPages()`。
起初,我认为最合乎逻辑的做法是直接从 `List` 继承:
```csharp
public class Library : List
{
public List FindByAuthor(string author)
{
return this.Where(b => b.Author == author).ToList();
}
public int GetTotalPages()
{
return this.Sum(b => b.Pages);
}
}
```
看起来一切正常,但我在 Stack Overflow 上读到这是一种不好的实践。人们写道“不应该继承 List”。但我不太明白为什么?这很方便——立即获得列表的所有方法(Add、Remove、索引器等)。我的代码变得简短而优雅。
你能用例子解释一下这有什么问题吗?