You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中不使用List,实现类似List.Add的数组元素添加方法

实现类似List.Add的数组元素添加功能

C#中的数组是固定长度的,一旦创建就无法修改长度,因此没有内置的.Add()方法。要实现类似功能,必须手动创建新数组,复制原数组的所有元素后,再把新元素追加到新数组的末尾。

针对你的代码修改后的版本

直接调整你提供的MultiplyByLength方法,实现元素添加逻辑:

public class Program
{
    public static int[] MultiplyByLength(int[] arr)
    {
        int[] finallist = new int[0];
        int curnum = 0;
        foreach(int item in arr)
        {
            curnum = item * arr.Length;
            // 模拟Add操作:创建长度+1的新数组
            int[] newArray = new int[finallist.Length + 1];
            // 复制原数组元素到新数组
            Array.Copy(finallist, newArray, finallist.Length);
            // 将新元素放入新数组的最后位置
            newArray[newArray.Length - 1] = curnum;
            // 替换原数组为新数组
            finallist = newArray;
        }
        return finallist;
    }
}

封装成可复用的工具方法

如果需要多次使用类似Add的功能,可以封装一个通用方法:

public static class ArrayHelper
{
    public static T[] Add<T>(T[] originalArray, T item)
    {
        // 创建长度+1的新数组
        T[] newArray = new T[originalArray.Length + 1];
        // 复制原数组所有元素
        Array.Copy(originalArray, newArray, originalArray.Length);
        // 追加新元素到末尾
        newArray[newArray.Length - 1] = item;
        return newArray;
    }
}

使用该工具方法后,你的MultiplyByLength方法可以简化为:

public class Program
{
    public static int[] MultiplyByLength(int[] arr)
    {
        int[] finallist = new int[0];
        int curnum = 0;
        foreach(int item in arr)
        {
            curnum = item * arr.Length;
            finallist = ArrayHelper.Add(finallist, curnum);
        }
        return finallist;
    }
}

注意事项

  • 这种方式每次添加元素都要创建新数组并复制元素,性能不如List(List会预分配容量,减少扩容次数),如果需要频繁添加元素,建议优先使用List<T>;若必须用数组,这是唯一可行的实现方式。
  • Array.Copy是高效的数组复制方法,性能优于手动循环复制元素。

内容的提问来源于stack exchange,提问作者BORBZABY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 18:54:57