【问题标题】:Error when trying to copy list to array [closed]尝试将列表复制到数组时出错[关闭]
【发布时间】:2013-10-20 20:46:55
【问题描述】:

我总是出错:

.exe 中出现“System.IndexOutOfRangeException”类型的未处理异常 附加信息:索引超出了数组的范围。

public List<SomeObject> hCL = new List<SomeObject>();
SomeObject[] cl_ = clients.GetCLValue(1, 1);

    for (int i = 1; i <= 5; i++)
    {
       SomeObject[] c = clients.GetCLValue(1, i).ToArray();
       c[i].LanguageId = i;                
       hCL.Add(c[i]);
    } 

GetCLValue 返回数据列表,但我无法将这些数据移动到数组 为什么这些错误总是出现? c# 不应该创建可以存储数据的新对象吗?

【问题讨论】:

  • 集合是基于的。
  • 如何根据工作规范使收集非零
  • 为什么让它们非零基?为什么不使用从零开始的索引?
  • 很难理解您的代码中的预期逻辑,请您尝试解释一下您想要做什么?
  • 好的,那么请在SomeObject[] c = clients.GetCLValue(1, i).ToArray();c[i].LanguageId = i;之间添加以下行Console.WriteLine("Array size: {0}; Index: {1}", c.Lenght, i)并显示输出

标签: c# arrays list error-handling


【解决方案1】:

为什么不去

SomeObject[] cl = hCL.ToArray() ;

【讨论】:

  • 以及用空转换列表获取空数组....您需要放入名为 GetCLValue 的 SomeObject 数组方法
  • 如果你想要一个空数组让我们说 5 SomeObjects 那么: SomeObject[] cl = new SomeObject[5];
  • 在回答之前阅读我的问题,我没有搜索空对象 hCL.ToArray() 不包含任何内容,因此将这些空列表复制到 SomeObject 数组不是正确答案。
猜你喜欢
  • 2021-03-08
  • 1970-01-01
  • 2016-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-31
  • 1970-01-01
  • 2014-02-03
相关资源
最近更新 更多