在C#中为List定义运算符

时间:2016-01-11 16:04:56

标签: c# matrix operator-keyword

我想在C#中为List定义一些操作。 例如,添加(+)和转置(')。 但是,编译代码时出现错误。 我定义了一个继承自List>的矩阵类。 而且,我实现了+和'运营商。 第一个是好的但是当我在主要调用它时,会出现错误。 第二种方法甚至无法编译。 有人可以帮忙吗? 非常感谢。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    class Matrix : List<List<double>>
    {
        public static Matrix operator +(Matrix a, Matrix b)
        {
            Matrix c = new Matrix();
            int i, j;

            for (i = 0; i < a.Count; i++)
            {
                for (j = 0; j < a[1].Count; j++)
                {
                    c[i][j] = a[i][j] + b[i][j];
                }

            }

            return c;

        }


        public static Matrix operator ' (Matrix a)
        {
            Matrix b = new Matrix();
            int i, j;

            for (i = 0; i<a.Count; i++)
            {
                for (j = 0; j < a[1].Count; j++)
                {
                 b[j][i] = a[j][i];
                }

            }

            return b;

        }


        public static int Main(string[] args)
        {

            Matrix x = new Matrix { new List<double> { 1, 2, 5, 2 }, new List<double> { 3, 4, 0, 7 } };
            Matrix y = new Matrix { new List<double> { 1, 2, 5, 2 }, new List<double> { 3, 4, 0, 7 } };
            Matrix z = new Matrix();

            z = x + y;

            Console.WriteLine(z);

            return 0;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

'不是有效的运算符。可重载的操作符是:
一元:+ - ! 〜++ - 真假 二进制:+ - * /%&amp; | ^&lt;&lt; &GT;&GT; ==!=&lt; &GT; &lt; =&gt; =

其中一些也有限制。例如,比较运算符必须成对重载,并且移位运算符的第二个参数(&lt;&lt;&gt;&gt;)必须是int

看看:C# overloadable operators