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

如何在数组指定位置添加新元素?解决随机数存入数组CS0150报错

问题解决:CS0150错误及数组元素操作

一、CS0150错误原因及修复

你的代码报错有两个核心问题:

  1. 使用变量x指定数组长度的同时,用初始化器{ rnd.Next() }赋值,C#要求这种场景下数组长度必须是常量值,而x是运行时变化的变量,直接触发CS0150错误。
  2. 循环逻辑存在漏洞:每次循环都重新创建数组,之前生成的随机数会被直接丢弃;且当x=0时,创建的是长度为0的数组,访问cards[x]会触发索引越界异常。

修复后的代码可以直接创建固定长度数组,逐个赋值:

int x = 0;
Random rnd = new Random();
// 提前创建长度为5的目标数组
int[] cards = new int[5];
while (x != 5)
{
    cards[x] = rnd.Next();
    Console.WriteLine(cards[x]);
    x++;
}

用for循环实现会更简洁:

Random rnd = new Random();
int[] cards = new int[5];
for (int x = 0; x < cards.Length; x++)
{
    cards[x] = rnd.Next();
    Console.WriteLine(cards[x]);
}

二、数组指定位置添加/插入元素

C#中的数组是固定长度的,一旦创建就无法修改长度,所以不能直接在指定位置"创建新元素"。如果需要动态调整集合长度或插入元素,推荐使用List<int>这类动态集合,它自带插入方法:

Random rnd = new Random();
List<int> cardList = new List<int>();
// 先添加几个初始元素
cardList.Add(rnd.Next());
cardList.Add(rnd.Next());
// 在索引1的位置插入新随机数
cardList.Insert(1, rnd.Next());
// 输出验证
foreach (int num in cardList)
{
    Console.WriteLine(num);
}

如果必须使用数组,需要手动创建新数组,复制原数组元素并插入新值:

int[] originalArray = { 1, 3, 4 };
int insertIndex = 1;
int newValue = 2;
// 创建长度+1的新数组
int[] newArray = new int[originalArray.Length + 1];

// 复制插入位置之前的元素
Array.Copy(originalArray, newArray, insertIndex);
// 插入新值
newArray[insertIndex] = newValue;
// 复制插入位置之后的剩余元素
Array.Copy(originalArray, insertIndex, newArray, insertIndex + 1, originalArray.Length - insertIndex);

// 输出新数组内容
foreach (int num in newArray)
{
    Console.WriteLine(num);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 07:05:30