Convert IList to array in C#

前端 未结 4 1978
后悔当初
后悔当初 2021-01-08 00:24

I want to convert IList to array: Please see my code:

IList list = new ArrayList();
list.Add(1);
Array array = new Array[list.Count];
list.CopyTo(array, 0);
         


        
4条回答
  •  粉色の甜心
    2021-01-08 01:21

    You're creating an array of Array values. 1 is an int, not an Array. You should have:

    IList list = new ArrayList();
    list.Add(1);
    Array array = new int[list.Count];
    list.CopyTo(array, 0);
    

    or, ideally, don't use the non-generic types to start with... use List instead of ArrayList, IList instead of IList etc.

    EDIT: Note that the third line could easily be:

    Array array = new object[list.Count];
    

    instead.

提交回复
热议问题