添加到 ICollection
我目前正在编写一个C#项目,我需要对该项目进行单元测试。对于我需要进行单元测试的方法之一,我使用 ICollection,它通常是从列表框的所选项目中填充的。
当我为该方法创建单元测试时,它会创建行
ICollection icollection = null; //Initialise to an appropriate value
How can I create an instance of this ICollection and an item to the collection?
I am currently writing a C# project and I need to do unit testing for the project. For one of the methods that I need to unit test I make use of an ICollection which is normally populated from the selected items of a list box.
When I create a unit test for the method it creates the line
ICollection icollection = null; //Initialise to an appropriate value
How can I create an instance of this ICollection and an item to the collection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
ICollection
是一个接口,您不能直接实例化它。您需要实例化一个实现 ICollection 的类;例如,列表
。另外,ICollection
界面 没有Add
方法 - 您需要实现IList
或IList
的方法。例子:
ICollection
is an interface, you can't instantiate it directly. You'll need to instantiate a class that implementsICollection
; for example,List<T>
. Also, theICollection
interface doesn't have anAdd
method -- you'll need something that implementsIList
orIList<T>
for that.Example:
与某些评论相反,
IList
确实实现了ICollection
,至少据我所知。Contrary to some comments,
IList<T>
does implementICollection
, at least as far as I can tell.假设您有一个字符串集合,那么代码将是:
Let's say you will have a collection of strings, then the code will be:
我相信您需要将 ICollection 接口继承到新类中才能使用它。
如何实现 ICollection
I believe you need to inherit the
ICollection
interface into a new class before you can use it.How to implement ICollection
您可以做的是创建一个实现 ICollection 的类型,然后在测试中使用它。列表或集合可用于创建对象的实例。我想另一个问题是列表框的项目是什么类型。只需使用 .Add(...) 方法即可将项目添加到列表或集合中,这非常简单。
您需要对这个系列做一些更具体的事情吗?
What you can do is create a type that implements ICollection and from there make use of it in your testing. A List or Collection would work for creating an instance of the object. I guess another question would be what type are the items of the list box. Adding items to the List or Collection is pretty trivial just using the .Add(...) method.
Is there something more specific you need to be doing with this collection?