首页 > 解决方案 > 将 ArrayList 手动转换为 Array C#

问题描述

我已经完成了类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#arraysarraylist

解决方案


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

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

用法:

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

推荐阅读