【发布时间】:2021-05-27 15:05:22
【问题描述】:
我有一个继承 List 的集合类。我想要该类上的一个方法,它可以遍历基类列表中的项目。
目前我有这个:
public class Invoices : List<Invoice>
{
public string ToString()
{
string cOP = "";
int i;
Invoice oInvoice;
cOP += string.Format("Invoices.Count = {0}\r\n", base.Count);
foreach (Invoice oInvoice in base)
{
cOP += oInvoice.ToString();
}
return cOP;
}
}
但是我在 foreach 语句中的 base 上得到了编译时错误,“Use of keyword 'base' is not valid in this context”。
我尝试将 base 替换为:
- base.ToArray() - 这确实有效,但我认为 List 的全部意义在于它是可枚举的。
- base.ToList() - “'System.Collections.Generic.List
' 不包含 'ToList' 的定义”
我是否需要将 List 转换为 Array 以对其进行迭代?当然我应该能够迭代列表吗?
【问题讨论】:
-
这里有一个提示,从
List<T>继承是一种不好的做法。 -
使用
this代替base? (注意:MS 指南说你应该继承自Collection<T>而不是List<T>) -
用 Eric Lipperts 的话来说:“你想扩展 List
机制还是想创建一个需要集合的业务对象”?我确定你想要后者,所以让它成为你班级的一个属性。 -
蒂姆是绝对正确的——你应该prefer composition over inheritance
标签: c# list inheritance ienumerable enumerable