如何在.NET 2.0中创建自定义集合
嗨,我想创建自定义集合,我从CollectionBase类派生我的自定义集合类,如下所示:
public class MyCollection : System.Collectio.CollectionBase { MyCollection(){} public void Add(MyClass item) { this.List.Add(item); } } class MyClass { public string name; }
我来问几个问题:
- 当我在.NET 3.5框架上工作时,这种方法是否正确和新。
- 我想从我的Web服务(WCF)中公开这个集合。我该怎么做?
- 我必须实现GetEnumerator吗?
- 这是否会绑定到DataGridView。
从List
派生有点无意义, 特别是现在它具有IEnumerable
构造函数和扩展方法的可用性。 除了Equals
, GetHashCode
和ToString
之外,它没有可以覆盖的虚方法。 (我想你可以从List
派生,如果你的目标是为列表实现Java的toString()function。)
如果要创建自己的强类型集合类并可能在添加/删除项时自定义集合行为,则需要从新的(到.NET 2.0)类型派生System.Collections.ObjectModel.Collection
,它具有受保护的虚拟方法,包括InsertItem
和RemoveItem
,您可以覆盖这些方法以在这些时间执行操作。 请务必阅读文档 – 这是一个非常容易派生的类,但您必须意识到公共/非虚拟和受保护/虚拟方法之间的区别。 🙂
public class MyCollection : Collection { public MyCollection() { } public MyCollection(IList list) : base(list) { } protected override void ClearItems() { // TODO: validate here if necessary bool canClearItems = ...; if (!canClearItems) throw new InvalidOperationException("The collection cannot be cleared while _____."); base.ClearItems(); } protected override void RemoveItem(int index) { // TODO: validate here if necessary bool canRemoveItem = ...; if (!canRemoveItem) throw new InvalidOperationException("The item cannot be removed while _____."); base.RemoveItem(index); } }
我认为你最好使用System.Collections.Generic中定义的容器类之一
- 当我在.NET 3.5框架上工作时,这种方法是否正确和新。
- 不,请使用列表或其他内容。
- 我想从我的Web服务(WCF)中公开这个集合。我该怎么做?
- 通过。 没有使用过WCF。
- 我必须实现GetEnumerator吗?
- 如果您使用标准的System.Collections.Generic容器类之一,请不要这样做。 它已经为你完成了
- 这是否会绑定到DataGridView。
- 任何支持IEnumerable的标准集合都会很好地绑定到控件。 如果要进行排序和过滤,可以查看使用IBindingListView。
如果你想要自己的集合类,你也可以从generics集合inheritance到非generics类,例如:
public class MyCollection : List { }
这样您就可以获得列表的所有function(例如)。 你只需要添加一些构造函数。
为什么不使用通用集合?
using System; using System.Collections.Generic; namespace Test { class MyClass { } class Program { static void Main(string[] args) { // this is a specialized collection List list = new List (); // add elements of type 'MyClass' list.Add(new MyClass()); // iterate foreach (MyClass m in list) { } } } }
编辑 :Ashu,如果你想对添加和删除操作进行一些validation,你可以使用generics集合作为专门集合的成员:
using System; using System.Collections.Generic; namespace Test { class MyClass { } class MyClassList { protected List _list = new List (); public void Add(MyClass m) { // your validation here... _list.Add(m); } public void Remove(MyClass m) { // your validation here... _list.Remove(m); } public IEnumerator GetEnumerator() { return _list.GetEnumerator(); } } class Program { static void Main(string[] args) { MyClassList l = new MyClassList(); l.Add(new MyClass()); // iterate foreach (MyClass m in l) { } } } }
也许我在这里遗漏了一些东西,但是如果你只需要添加validation,为什么不从generics集合inheritance并覆盖New()
Remove()
或任何其他方法。
class CustomeCollection : List { public new void Add(T item) { //Validate Here base.Add(item); } public new void Remove(T item) { //Validate Here base.Remove(item); } }