简体   繁体   English

如何转换ReadOnlyCollection <T> 到T []?

[英]How to cast a ReadOnlyCollection<T> to T[]?

I have a class with a ReadOnlyCollection property. 我有一个具有ReadOnlyCollection属性的类。 I need to convert that ReadOnlyCollection into a int[]. 我需要将ReadOnlyCollection转换为int []。 How can this be done? 如何才能做到这一点? Is it possible to do this without iterating over the collection? 是否可以在不迭代集合的情况下执行此操作?

No, it's not possible to convert a ReadOnlyCollection to an array without iterating it. 不,如果不迭代它,就不可能将ReadOnlyCollection转换为数组。 That would turn the collection to a writable collection, breaking the contract of being read-only. 这会将集合变成可写集合,违反了只读的合同。

There are different ways of iterating the collection that spares you of writing the loop yourself, for example using the CopyTo method 有不同的方法来迭代集合,这使您不必自己编写循环,例如使用CopyTo方法

int[] collection = new int[theObject.TheProperty.Count];
theObject.TheProperty.CopyTo(collection, 0);

Or the extension method ToArray: 或者扩展方法ToArray:

int[] collection = theObject.TheProperty.ToArray();

当然使用LINQ扩展方法myReadOnlyCollection.ToArray()

There aren't any ways without iterating. 没有迭代就没有任何方法。 There is a built-in method to do this though: 有一个内置的方法来做到这一点:

T[] myArray;
myCollection.CopyTo(myArray, 0);

or using Linq: 或使用Linq:

var myArray = myCollection.ToArray();

If you're in the later versions of the .NET framework ReadOnlyCollection<T> implements IEnumerable<T> . 如果您使用的是.NET框架的更高版本,则ReadOnlyCollection<T>实现IEnumerable<T> IEnumerable<T> has an extension method ToArray() . IEnumerable<T>有一个扩展方法ToArray() So you'd use that extension method like so... 所以你会像这样使用那种扩展方法......

var readOnly = new ReadOnlyCollection<int>(new List<int>() {1,2,3,4,5});
var myArray = readOnly.ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM