二元运算符的参数之一必须是包含类型 c#
one of the parameters of a binary operator must be the containing type c#
public static int[,] operator *(int[,] arr1, int[,] arr2)
{
int sum;
int[,] res = new int[arr1.GetLength(0), arr2.GetLength(1)];
for (int i = 0; i < arr1.GetLength(0); i++)
{
for (int j = 0; j < arr2.GetLength(1); j++)
{
sum = 0;
for (int k = 0; k < arr1.GetLength(1); k++)
{
sum = sum + (arr1[i, k] * arr2[k, j]);
}
res[i, j] = sum;
//Console.Write("{0} ", res[i, j]);
}
//Console.WriteLine();
}
return res;
}
这里我试图重载 * 运算符来将两个矩阵相乘..
但编译器不断向我显示错误...
" 二元运算符的参数之一必须是包含类型 c#"
请告诉我我的代码中有什么问题以及如何解决它..
编译器已经告诉您哪里出了问题 - 但引用 C# 5 规范的第 7.3.2 节:
User-defined operator declarations always require at least one of the parameters to be of the class or struct type that contains the operator declaration. Thus, it is not possible for a user-defined operator to have the same signature as a predefined operator.
换句话说,如果有:
class Foo
{
public static int[,] operator *(int[,] arr1, Foo arr2)
{
...
}
}
... 因为第二个操作数是声明类型。但在你的情况下,两个操作数都是 int[,]
.
您可以做的是添加一个扩展方法:
public static class ArrayExtensions
{
public static int[,] Times(this int[,] arr1, int[,] arr2)
{
...
}
}
那么你可以:
int[,] x = ...;
int[,] y = ...;
int[,] z = x.Times(y);
另一种解决方案 - 更好的解决方案,IMO,将声明您自己的 Matrix
class 来封装矩阵运算。然后你可以定义你自己的乘法运算符:
public static Matrix operator *(Matrix left, Matrix right)
...而且您不会干扰 int[,]
不打算被视为矩阵的数组。
public static int[,] operator *(int[,] arr1, int[,] arr2)
{
int sum;
int[,] res = new int[arr1.GetLength(0), arr2.GetLength(1)];
for (int i = 0; i < arr1.GetLength(0); i++)
{
for (int j = 0; j < arr2.GetLength(1); j++)
{
sum = 0;
for (int k = 0; k < arr1.GetLength(1); k++)
{
sum = sum + (arr1[i, k] * arr2[k, j]);
}
res[i, j] = sum;
//Console.Write("{0} ", res[i, j]);
}
//Console.WriteLine();
}
return res;
}
这里我试图重载 * 运算符来将两个矩阵相乘.. 但编译器不断向我显示错误...
" 二元运算符的参数之一必须是包含类型 c#"
请告诉我我的代码中有什么问题以及如何解决它..
编译器已经告诉您哪里出了问题 - 但引用 C# 5 规范的第 7.3.2 节:
User-defined operator declarations always require at least one of the parameters to be of the class or struct type that contains the operator declaration. Thus, it is not possible for a user-defined operator to have the same signature as a predefined operator.
换句话说,如果有:
class Foo
{
public static int[,] operator *(int[,] arr1, Foo arr2)
{
...
}
}
... 因为第二个操作数是声明类型。但在你的情况下,两个操作数都是 int[,]
.
您可以做的是添加一个扩展方法:
public static class ArrayExtensions
{
public static int[,] Times(this int[,] arr1, int[,] arr2)
{
...
}
}
那么你可以:
int[,] x = ...;
int[,] y = ...;
int[,] z = x.Times(y);
另一种解决方案 - 更好的解决方案,IMO,将声明您自己的 Matrix
class 来封装矩阵运算。然后你可以定义你自己的乘法运算符:
public static Matrix operator *(Matrix left, Matrix right)
...而且您不会干扰 int[,]
不打算被视为矩阵的数组。