Ash*_*shu 4 c# generics wcf datagridview
嗨,我想创建自定义集合,我从CollectionBase类派生我的自定义集合类,如下所示:
public class MyCollection : System.Collectio.CollectionBase
{
MyCollection(){}
public void Add(MyClass item)
{
this.List.Add(item);
}
}
class MyClass
{
public string name;
}
Run Code Online (Sandbox Code Playgroud)
我来问几个问题:
派生List<T>
是有点无意义的,特别是现在它具有IEnumerable<T>
构造函数和扩展方法的可用性.它可以除了可以覆盖无虚方法Equals
,GetHashCode
和ToString
.(我想你可以从List<T>
你的目标是为列表实现Java的toString()功能中获得.)
如果要创建自己的强类型集合类并且可能在添加/删除项时自定义集合行为,则需要从新的(到.NET 2.0)类型派生,该类型System.Collections.ObjectModel.Collection<T>
具有受保护的虚拟方法,包括InsertItem
并且RemoveItem
您可以覆盖以在那些时间执行操作.请务必阅读文档 - 这是一个非常容易派生的类,但您必须意识到公共/非虚拟和受保护/虚拟方法之间的区别.:)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6391 次 |
最近记录: |