Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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#_List - Fatal编程技术网

C#试图交换列表中的一个元素,但最终交换了所有元素

C#试图交换列表中的一个元素,但最终交换了所有元素,c#,list,C#,List,我制作了一个矩阵对象,如下所示: using System; using System.Collections.Generic; public class Matrix { public List<List<float>> rows = new List<List<float>>(); public Matrix() { } public Matrix(List<List<float>> Rows

我制作了一个矩阵对象,如下所示:

using System;
using System.Collections.Generic;

public class Matrix
{
  public List<List<float>> rows = new List<List<float>>();

  public Matrix()
  {

  }

  public Matrix(List<List<float>> Rows)
  {
    rows = Rows;
  }
使用系统;
使用System.Collections.Generic;
公共类矩阵
{
公共列表行=新列表();
公共矩阵()
{
}
公共矩阵(列表行)
{
行=行;
}
试图定义一个函数,矩阵乘法。然而,当我试图访问矩阵中的元素(I,j)并交换它时,它交换该列中的每个元素

public static Matrix operator*(Matrix A, Matrix B)
    {
      List<List<float>> input = new List<List<float>>();
      List<float> input_list = new List<float>();

      for(int i = 0; i < B.rows.Count; i++)
      {
        input_list.Add(0);
      }

      for(int i = 0; i < A.rows.Count; i++)
      {
        input.Add(input_list);
      }

      Matrix C = new Matrix(input);

      Console.WriteLine(C);
      // output
      // |0 0 0|
      // |0 0 0|
      // |0 0 0|
      C.rows[0][0] = 69;
      // output
      // |69 0 0|
      // |69 0 0|
      // |69 0 0| ???          
      Console.WriteLine(C);
      return C;
公共静态矩阵运算符*(矩阵A、矩阵B)
{
列表输入=新列表();
列表输入_List=新列表();
for(int i=0;i
我希望C.rows[0][0]=69;会产生输出 |69 0 0| |0 0 0| |0 0 0 |

input.Add(input_list);
替换为
input.Add(input_list.ToList());
,因为您需要不同的列表实例


但是,这是一种绝对可怕的构建矩阵的方法。您正在使用计算机科学中最优化的数据结构之一,并试图通过“玩面团”和“希望”将其拼凑在一起。尤其糟糕的是,由于.Net已经进行了大量优化和矢量化。

这是因为您正在添加对象引用。 使用System.Linq

 for(int i = 0; i < A.rows.Count; i++)
 {
    input.Add(input_list.Select(item => (T)item.Clone()).ToList());
 }
for(int i=0;i(T)item.Clone()).ToList());
}

A
List
是一个
input.Add(input\u List);多次添加同一个实例
input\u List
。显然你想要
input.Add(new List());
,但是列表一开始就不是一个很好的方法。这会起作用,但Blindy的答案更好,代码更少