【发布时间】:2013-07-25 08:35:29
【问题描述】:
您好,我想为数组操作写一些扩展,例如:
矩阵产品
public static double[][] operator *(double[][] matrixA, double[][] matrixB)
MatrixVectorProduct
public static double[] operator *(double[][] matrix, double[] vector)
还有更多
我为什么要这个?因为您可能知道目前在 c# 中实现了非此类操作,如果我可以说 matrixC = matrixA * matrixB; 而不是 matrixC = MatrixProduct(matrixA,matrixB);,那感觉更自然,那么有没有办法做到这一点?
因为如果我这样做:
public static class ArrayExtension
{
public static double[] operator *(double[][] matrix, double[] vector)
{
// result of multiplying an n x m matrix by a m x 1 column vector (yielding an n x 1 column vector)
int mRows = matrix.Length; int mCols = matrix[0].Length;
int vRows = vector.Length;
if (mCols != vRows)
throw new InvalidOperationException("Non-conformable matrix and vector in MatrixVectorProduct");
double[] result = new double[mRows]; // an n x m matrix times a m x 1 column vector is a n x 1 column vector
Parallel.For(0, mRows, i =>
{
var row = matrix[i];
for (int j = 0; j < mCols; ++j)
result[i] += row[j] * vector[j];
});
return result;
}
}
一个异常告诉我我不能将一个静态类和一个用户定义的运算符结合起来,所以有解决办法吗?
【问题讨论】:
-
您始终可以定义自己的
Matrix类并为该类型指定运算符。实际上,我认为这里没有其他方法。 -
但我不想重新发明轮子:(
-
另外,这不会是Extension Method,因为第一个参数前面没有
this。 -
@WiiMaxx 这里没有太多的重新发明,你的
Matrix类可以只包装一个锯齿状数组并公开所需的运算符/方法(例如Transpose)。可以说,它会更干净(语义上),因为锯齿状数组并不一定意味着“矩阵”。 -
@Corak 你是对的 :) 还没有看到它,所以它变得更糟,因为它看起来我也不能在那里使用它 :D
标签: c# operators operator-overloading overriding