当前位置: 首页 > 编程语言 > C#

实现IList接口分享

时间:2023-04-11 10:52:59 C#

IList接口的实现我是仿制药新手。我想通过从IList接口派生它来实现我自己的集合。你能给我一些实现IList接口的类的链接,或者给我提供至少实现Add和Remove方法的代码吗?除非您有非常令人信服的理由这样做,否则最好的办法是从System.Collections.ObjectModel.Collection继承,因为它拥有您需要的一切。请注意,虽然IList的实现者不需要将this[int](索引器)实现为O(1)(本质上是恒定时间访问),但强烈建议您这样做。除了从List派生,您还可以使用FacinList并向外观类添加更多功能。类MyCollection:IList{privatereadonlyIList_list=newList();#region实现IEnumerablepublicIEnumeratorGetEnumerator(){return_list.GetEnumerator();}IEnumeratorIEnumerable.GetEnumerator(){返回GetEnumerator();}#endregion#regionICollection的实现publicvoidAdd(Titem){_list.Add(item);}publicvoidClear(){_list.Clear();}publicboolContains(Titem){return_list.Contains(item);}publicvoidCopyTo(T[]array,intarrayIndex){_list.CopyTo(array,arrayIndex);}publicboolRemove(Titem){return_list.Remove(item);}publicintCount{get{return_list.Count;}}publicboolIsReadOnly{get{return_list.IsReadOnly;}}#endregion#regionIList的实现publicintIndexOf(Titem){return_list.IndexOf(item);}publicvoidInsert(intindex,Titem){_list.Insert(index,item);}publicvoidRemoveAt(intindex){_list.RemoveAt(index);}publicTthis[intindex]{get{ret瓮_列表[索引];}设置{_list[索引]=值;}}#endregion#regionYourAddedStuff//将新功能添加到您的收藏中。#endregion}你可以查看Mono项目以获得完整的源代码,你可以看到一些类是如何实现的。例如“System.Collections.Generics.List”。在大多数情况下,您可以简单地使用或派生自List。如果您从List派生,您会自动获得添加和删除的实现。从Listin继承通常是最快的方法,但如果您需要从另一个类(例如ContextBoundObject等)继承,可以稍后限制。实施IList非常快,并且如上所述,提供了更大的灵活性。以上就是C#学习教程的全部内容:实现IList接口的共享。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: