【发布时间】:2021-06-02 16:55:19
【问题描述】:
我制作了一个 Matrix 对象,如下所示:
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;
}
并尝试定义一个函数,矩阵乘法。但是,当我尝试访问矩阵中的元素 (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;
我希望 C.rows[0][0] = 69;导致输出 |69 0 0| |0 0 0| |0 0 0|
【问题讨论】:
-
List是 reference type。input.Add(input_list);多次添加同一个实例input_list。显然你想要input.Add(new List<float>());,但首先列出列表并不是represent a matrix 的好方法。