Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 列表索引错误:索引超出范围_C#_Asp.net - Fatal编程技术网

C# 列表索引错误:索引超出范围

C# 列表索引错误:索引超出范围,c#,asp.net,C#,Asp.net,我有两个列表,我想将数据从一个列表复制到另一个列表,但出现以下错误: 索引超出范围。必须为非负数且小于集合的大小。 参数名称:索引 这是我的密码: static IList<Common.Data.Driver> Stt_driverList = new List<Common.Data.Driver>(); List<Common.Data.Driver> driverList = new List<Common.Data.Driver>();

我有两个列表,我想将数据从一个列表复制到另一个列表,但出现以下错误:

索引超出范围。必须为非负数且小于集合的大小。
参数名称:索引

这是我的密码:

static  IList<Common.Data.Driver> Stt_driverList = new List<Common.Data.Driver>();
List<Common.Data.Driver> driverList = new List<Common.Data.Driver>();

for (int i = 0; i < driverList.Count; i++)
{
    //Fill in The Static Driver List
    Stt_driverList[i] = driverList[i]; 
}
静态IList Stt_driverList=new List();
列表驱动器列表=新列表();
for(int i=0;i
您应该使用Stt_driverList.Add(…),还可以查看函数AddRange()。

您不能使用索引器来增加列表的大小;仅用于修改现有条目。您可以使用
添加
。。。但一次复制整个列表会更简单:

Stt_driverList = new List<Common.Data.Driver>(driverList);
Stt_driverList=新列表(driverList);
该构造函数只在一次调用中执行浅层复制


如果这不是您想要的,可能仍然有一种避免显式循环的好方法-请提供更多详细信息,我们可能会为您提供更多帮助。

Stt\u driverList
在开始循环时不包含任何项,因此您不能按索引引用元素。尝试使用
Add
方法:

static IList Stt_driverList = new List();
IList driverList = new List();
for (int i = 0; i < driverList.Count; i++)
{
    //Fill in The Static Driver List
    Stt_driverList.Add(driverList[i]);
}
静态IList Stt_driverList=new List();
IList driverList=新列表();
for(int i=0;i