实现IList接口
我是泛型新手。 我想通过从 IList
接口派生来实现我自己的集合。
您能否为我提供一些实现 IList
接口的类的链接,或者为我提供至少实现 Add
和 Remove
的代码方法?
I am new to generics. I want to implement my own collection by deriving it from IList<T>
interface.
Can you please provide me some link to a class that implements IList<T>
interface or provide me a code that at least implements Add
and Remove
methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
从 List 继承通常是最快的方法,但如果您需要从另一个类(例如 ContextBoundObject 等)继承,则可能会在以后受到限制。 实现 IList 非常快,并且如上所述,它提供了更多的灵活性。
Inheriting from List is often the quickest approach but can be limiting later on down the line if you need to inherit from another class (e.g. ContextBoundObject etc.). It's pretty quick to implement IList and as pointed out above, it gives a lot more flexibility.
在大多数情况下,您可以简单地使用
List
或从List
派生。 如果您从List
派生,您将自动获得“添加”和“删除”的实现。In most cases you can simply use
List<T>
or derive fromList<T>
. If you derive fromList<T>
you will automatically get the implementation for Add and Remove.您可以查看 Mono 项目。 有完整的源代码,您可以看看一些类是如何实现的。 例如“System.Collections.Generics.List”。
You can look at Mono project. There is available complete source codes, sou you can look how are some classes implemented. For example "System.Collections.Generics.List<T>".
Visual Studio 提供了 IList 等接口的自动完整工作实现。
您只需要编写类似以下代码的代码:(
虽然该行
很重要!)
然后单击灯泡符号或将光标放在 IList<> 上 然后按 Strg + "." 您将看到提供的几种实现,例如:
Visual Studio offers an automatic full working implementation of interfaces like IList<>.
You need only to write something like this code:
(while the line
is the important one!)
Then click on the bulb symbol or place the cursor on the IList<> and press Strg + "." You will become several implementations offered, like:
除非您有非常令人信服的理由这样做,否则最好的选择是从 System.Collections.ObjectModel.Collection继承,因为它拥有您需要的一切。
请注意,尽管
IList
的实现者不需要将this[int]
(索引器)实现为 O(1)(基本上是恒定时间访问) ,强烈建议您这样做。Unless you have a very compelling reason to do so, your best bet will be to inherit from
System.Collections.ObjectModel.Collection<T>
since it has everything you need.Please note that although implementors of
IList<T>
are not required to implementthis[int]
(indexer) to be O(1) (basically, constant-time access), it's strongly recommended you do so.除了从
List
派生之外,您还可以外观List
并向外观类添加更多功能。In addition to deriving from
List<T>
, you can facadeList<T>
and add more features to your facade class.