c# - 二元运算符的参数之一必须是包含类型 c#

标签 c# .net visual-studio-2010 visual-c#-express-2010

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 类来封装矩阵操作。然后您可以定义您自己的乘法运算符:

public static Matrix operator *(Matrix left, Matrix right)

...并且您不会干扰不应被视为矩阵的 int[,] 数组。

关于c# - 二元运算符的参数之一必须是包含类型 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38158721/

相关文章:

c# - 使用 C# 客户端处理 Oracle 密码过期和宽限期

c# - 使用 JSON.Net 验证 JsonConvert.DeserializeObject(想想 "try parse")的结果

.NET 挫折 - Process.GetProcessById 返回新引用

c# - 您可以在一个项目中混合使用 .net 语言吗?

c# - 为什么要在窗体上放置标准对话框?

c# - 为什么 switch 表达式会从周围的上下文中推断出表达式类型,而其他类型不明确的表达式却不会?

c# - 在基于文本的游戏中添加年龄错觉

visual-studio-2010 - NuGet升级问题

c++ - MSVC10 中的奇怪编译器错误

c# - 为每个循环创建 XName.Get In