【问题标题】:Converting ArrayList to Array manually C#将 ArrayList 手动转换为 Array C#
【发布时间】:2021-04-07 18:46:51
【问题描述】:

我做过List类,它实现了一个数组列表数据结构。它看起来像这样:

 class List
    {
        public int max;
        public int last;
        public int size;
        int[] arr ;
        
        public List(int n)
        {
            max = n;
            last = -1;
            arr = new int[max];
            size = 1;
        }

       
        public void addItem(int item)
        {
            if (isFull())
            { 
                Console.WriteLine("Memory overflow: item cannot be added to list.");
            }

            else
            { 
                arr[++last] = item;
            }
        }

我可以以某种方式将 List 转换为数组吗?

【问题讨论】:

    标签: c# arrays arraylist


    【解决方案1】:

    您可以向您的List 类添加一个公共方法,该方法返回arr 字段的副本:

    public int[] ToArray() => arr.ToArray();
    

    用法:

    List list = new List(1);
    list.addItem(1);
    int[] array = list.ToArray();
    

    【讨论】:

    • 此解决方案公开了内部arr 成员,该成员允许修改原始List 的状态:list.ToArray()[0]=123
    • @cly: 不再,因为现在它返回内部数组的副本:)
    猜你喜欢
    • 1970-01-01
    • 2012-04-13
    • 2013-02-13
    • 2017-06-02
    • 2020-04-26
    • 2019-05-17
    • 2019-04-10
    • 2012-03-16
    • 2015-11-10
    相关资源
    最近更新 更多