2012-01-16 38 views
0

C#中可能不使用泛型從System.Collections.IList接口獲取數組嗎?如何從IList接口獲取數組

編輯:我需要一些方法將集合轉換爲數組。我的收藏已分配給IList。這有可能做到嗎?我不知道我的收藏的真正實施,所以我不能做像這樣 int [] arr =(ArrayList)list.ToArray();

+0

這不是真的清楚你想要達到的目標。請更具體一些。 – 2012-01-16 12:05:02

+0

CopyTo()? http://msdn.microsoft.com/en-us/library/system.collections.icollection.copyto.aspx – IanNorton 2012-01-16 12:05:38

+0

@Jon Skeet請參閱我的編輯 – 2012-01-16 12:08:37

回答

2

可以使用CopyTo方法:

IList list = new List<string>(new[] { "one", "two", "three" }); 
string[] array = new string[list.Count]; 
list.CopyTo(array, 0); 
+0

這使用泛型 – 2012-01-16 12:07:57

+3

@ Neil:是的,源列表是通用的,但它只能通過非通用的IList接口使用。 – 2012-01-16 12:08:32

+3

爲了強調Fredrik的觀點 - 你幾乎可以忽略第一行'='右邊的所有內容;這裏最重要的是「我們有一個名爲'list'的IList'」 – 2012-01-16 12:10:13