这应该做的伎俩,但我强烈建议对组成,在这里你将存储重新设计内部列出
public class MyItemList : List<MyItem>
{
public MyItemList(){}
public MyItemList(IEnumerable<MyItem> sequence): base(sequence) {}
public MyItemList cutOff(int count)
{
MyItemList result = new MyItemList(this.GetRange(0, count));
this.RemoveRange(0, count);
return result;
}
}
也可以考虑建立开放式泛型类型列表的像MyList<T> : List<T>
或MyList<T> : List<T> where T : MyItem
使类的客户端可以利用泛型的
编辑:好吧,我实现了通用版的List<T>
为扩展方法,这将有助于你更一般的逻辑来解释你的MyItemList类外
public static class ListExtensions
{
public static List<T> CutOff<T>(this List<T> list, int count)
{
var result = list.GetRange(0, count);
list.RemoveRange(0, count);
return result;
}
}
现在你可以
var list = new List<int> {1,2,3,4,5,6};
Console.WriteLine ("cutted items:");
Console.WriteLine (string.Join(Environment.NewLine, list.CutOff(2)));
Console.WriteLine ("items in list:");
Console.WriteLine (string.Join(Environment.NewLine, list));
打印:
cutted items:
1
2
items in list:
3
4
5
6
另注:
我建议这样做
public class MyItemList<T> : IList<T> where T : MyItem
{
private List<T> list;
//here will be implementation of all methods required by IList
//that will simply delegate to list field
}
注意,如果MyItemList
所有的逻辑是通用的(可以应用于List<T>
,如Cutoff
方法),你可能不需要单独的课程。此外where T : MyItem
是可选的,只有当你在MyItemList
您是否考虑过使用组合而不是继承? –
伊利亚是对的;它可能会更好地执行'IList',然后在内部使用私有'List '作为您的存储。这样,如果将来改变主意,您可以自由决定采用另一种实施策略。问自己一个'MyItemList' *是一种特殊的'List '*,还是它的作用就像是一个MyItems *列表。前者是类继承,后者是接口实现。 –
我同意你两个。另外,如果你只想添加一些额外的List函数,比如'CutOff',那么你可以使用扩展方法并且坚持使用泛型类型,即'List' –
sambomartin