问题描述
我想创建我的自定义集合,我正在从 CollectionBase 类派生我的自定义集合类,如下所示:
Hi I want to create my custom collection, I am deriving my custom collection class from CollectionBase class as below:
public class MyCollection : System.Collectio.CollectionBase
{
MyCollection(){}
public void Add(MyClass item)
{
this.List.Add(item);
}
}
class MyClass
{
public string name;
}
让我问几个问题:
- 这种方法是否正确且新颖,因为我正在研究 .NET 3.5 框架.
- 我想从我的网络服务 (WCF) 中公开这个集合.我该怎么做?
- 我是否必须实施 GetEnumerator?
- 这是否会绑定到 DataGridView.
推荐答案
从 List
派生有点毫无意义,尤其现在它有了 IEnumerable
构造函数和扩展方法的可用性.除了 Equals
、GetHashCode
和 ToString
之外,它没有可以覆盖的虚拟方法.(如果您的目标是为列表实现 Java 的 toString() 功能,我想您可以从 List
派生.)
Deriving from List<T>
is somewhat pointless, especially now that it has the IEnumerable<T>
constructor and the availability of extension methods. It has no virtual methods that you can override except Equals
, GetHashCode
, and ToString
. (I suppose you could derive from List<T>
if your goal was to implement Java's toString() functionality for lists.)
如果您想创建自己的强类型集合类并可能在添加/删除项目时自定义集合行为,您希望从新的(到 .NET 2.0)类型派生 System.Collections.ObjectModel.Collection
,有保护虚方法包括 InsertItem
和 RemoveItem
,您可以覆盖它们以在这些时间执行操作.请务必阅读文档 - 这是一个非常容易派生的类,但您必须意识到公共/非虚拟方法和受保护/虚拟方法之间的区别.:)
If you want to create your own strongly-typed collection class and possibly customize the collection behavior when items are add/removed, you want to derive from the new (to .NET 2.0) type System.Collections.ObjectModel.Collection<T>
, which has protected virtual methods including InsertItem
and RemoveItem
that you can override to perform actions at those times. Be sure to read the documentation - this is a very easy class to derive from but you have to realize the difference between the public/non-virtual and protected/virtual methods. :)
public class MyCollection : Collection<int>
{
public MyCollection()
{
}
public MyCollection(IList<int> 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);
}
}
这篇关于如何在 .NET 2.0 中创建自定义集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!