开发者

Convert from Array to ICollection<T>

What is the best way to acco开发者_如何学Gomplish this in C#?


Arrays of T are assignable to ICollection of T, as an array of T implements IList of T. IList of T itself extends ICollection of T, so you can simply assign an array to an ICollection.

class Foo {}

Foo [] foos = new Foo [12];
ICollection<Foo> foo_collection = foos;


Short answer:

Use ToList(). Don't rely on T[] being assignable to ICollection<T> unless you are aware of the following and know what you're doing.

If you need it read-only, it's better to use Array.AsReadOnly(T[]) and avoid the extra copy, and also avoid the problems detailed below.


Detailed answer:

Although array of T (ie. T[]) technically implements IList<T> (and ICollection<T> and IEnumerable<T>), it does not actually implement the entire IList<T> and ICollection<T> interfaces, as mentioned in the documentation:

...The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.

In other words, if you just cast the array to ICollection<T> you will get NotSupportedException as soon as you call any of the aforementioned methods.

So the best way to convert an array safely to an ICollection<T> would be to create a new object, such as using Linq's ToList():

T[] array;

// Will create a new list based on the current contents of the array
ICollection<T> collection = array.ToList();


In addition to the answer and the comment, if you want to go the other way, you use the ToArray() method on IEnumerable<T> (which ICollection<T> descends from).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜