【问题标题】:How to add an array to a list by value not by reference?如何按值而不是按引用将数组添加到列表中?
【发布时间】:2014-05-18 21:52:46
【问题描述】:

有没有办法通过值而不是通过引用将数组添加到数组列表中?

示例:以下打印出“6, 7, 8, 9, 10”。我希望它写出“1、2、3、4、5”。

int[] testArray = new int[5] { 1, 2, 3, 4, 5 };
List<int[]> testList = new List<int[]>();

testList.Add(testArray);

testArray[0] = 6;
testArray[1] = 7;
testArray[2] = 8;
testArray[3] = 9;
testArray[4] = 10;

foreach(int[] array in testList)
{
    Console.WriteLine("{0}, {1}, {2}, {3}, {4}", array[0], array[1], array[2], array[3], array[4]);
}

【问题讨论】:

  • 您需要创建数组的副本。
  • 所有内容都按值添加到列表中。您的困惑源于数组与所有对象一样不是 C# 中的值。 testArray 不是一个对象——它是一个引用(指向一个对象的指针)。

标签: c# arrays list pass-by-value


【解决方案1】:

复制一份:

testList.Add(testArray.ToArray());

【讨论】:

    【解决方案2】:

    您必须Clone() 数组,即创建数组的浅表副本并将其添加到列表中。

    testList.Add((int[])testArray.Clone());
    

    【讨论】:

      【解决方案3】:

      代替

      testList.Add(testArray);
      

      使用

      testList.Add(testArray.Clone() as int[]);
      

      【讨论】:

      • Clone() 返回对象,因此您必须将其类型转换回数组。
      猜你喜欢
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-28
      • 2015-03-11
      • 1970-01-01
      • 2011-01-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多