我将创建一个自定义矩阵类,只有一个二维数组来保存所有元素(我知道使用一维数组更快更好,但这不是这个实现的重点)。问题在于,我想要有一个构造函数,并且能够像这样做:
Matrix a = new Matrix(2,2){{1,2},{3,4}};
同时让一切正常运作。我遇到了“'Matrix'不包含定义为'Add'的方法,也没有扩展方法'Add'”等问题,但在查找后,我仍然无法找到足够强大的信息来定义Add()方法,以使其正常工作。以下是我目前所拥有的代码:
public class Matrix : IEnumerable
{
/* What we know abuot matricies
* - matricies are defined by rows, cols
* - addition is element-wise
*/
public IEnumerator GetEnumerator()
{
yield return m;
}
private void Add(double a)
{
// what exactly should go here anyway?
}
private double[,] m;
public double this[int rows, int cols]
{
get => m[rows, cols];
set => m[rows, cols] = value;
}
public Matrix(int rows, int cols)
{
m = new double[rows, cols];
}
...
}
那么,我该如何实现 Add() 方法呢?
m
矩阵的大小。这样,您就可以调用Matrix a = new Matrix(){{1,2},{3,4}};
。 - Magnetron