one of the parameters of a binary operator must be the containing type c#

怎甘沉沦 提交于 2021-02-20 06:25:50

问题


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;
    }

Here i am trying to overload * operator to multiply two matrices.. but the compiler keeps on showing me the error that..

" one of the parameters of a binary operator must be the containing type c#"

please tell me what is the problem in my code and how to solve it..


回答1:


The compiler is already telling you what is wrong - but to quote section 7.3.2 of the C# 5 specification:

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.

In other words, it would be fine to have:

class Foo
{
    public static int[,] operator *(int[,] arr1, Foo arr2)
    {
        ...
    }
}

... because then the second operand is the declaring type. But in your case both of the operands are int[,].

What you could do is add an extension method instead:

public static class ArrayExtensions
{
    public static int[,] Times(this int[,] arr1, int[,] arr2)
    {
        ...
    }
}

Then you could have:

int[,] x = ...;
int[,] y = ...;
int[,] z = x.Times(y);

Another solution - a better one, IMO, would be to declare your own Matrix class to encapsulate matrix operations. Then you can define your own multiplication operator:

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

... and you're not interfering with int[,] arrays which aren't intended to be treated as matrices.



来源:https://stackoverflow.com/questions/38158721/one-of-the-parameters-of-a-binary-operator-must-be-the-containing-type-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!