2

在我看来,这不仅仅是我的问题。
请不要重复关闭我的问题,因为我查看了这些问题但没有找到解决方案。

class Matrix<T> {
        private Int32 rows;
        private Int32 cols;
        private T[,] matrix;

        public Matrix() {
            rows = cols = 0;
            matrix = null;
        }

        public Matrix(Int32 m, Int32 n) {
            rows = m;
            cols = n;
            matrix = new T[m, n];
        }

        public T this[Int32 i, Int32 j] {
            get {
                if (i < rows && j < cols)
                    return matrix[i, j];
                else
                    throw new ArgumentOutOfRangeException();
            }
            protected set {
                if (i < rows && j < cols)
                    matrix[i, j] = value;
                else
                    throw new ArgumentOutOfRangeException();
            }
        }

        public Int32 Rows {
            get { return rows; }
        }

        public Int32 Cols {
            get { return cols; }
        }

        public static Matrix<T> operator+(Matrix<T> a, Matrix<T> b) { 
            if(a.cols == b.cols && a.rows == b.rows) {
                Matrix<T> result = new Matrix<T>(a.rows, a.cols);
                for (Int32 i = 0; i < result.rows; ++i)
                    for (Int32 j = 0; j < result.cols; ++j)
                        result[i, j] = a[i, j] + b[i, j];
                return result;
            }
            else
                throw new ArgumentException("Matrixes don`t match operator+ requirements!");
        }

        public static Matrix<T> operator-(Matrix<T> a, Matrix<T> b) {
            if (a.cols == b.cols && a.rows == b.rows) {
                Matrix<T> result = new Matrix<T>(a.rows, a.cols);
                for (Int32 i = 0; i < result.rows; ++i)
                    for (Int32 j = 0; j < result.cols; ++j)
                        result[i, j] = a[i, j] - b[i, j];
                return result;
            }
            else
                throw new ArgumentException("Matrixes don`t match operator- requirements!");
        }

你知道编译器告诉了什么:“运算符'-'不能应用于'T'和'T'类型的操作数”,即适用于所有运算符。
那么,对此最好的决定是什么?据我所知,接口不能包含运算符,因此唯一的方法是 T 类型的抽象基类。而且,正如我发现的那样,不能将操作符定义为抽象的。

4

3 回答 3

3

上一个答案(已经链接)解释了大部分内容;对于相关示例(在带有MiscUtil的 .NET 3.5 中)-Complex<T>

于 2009-04-24T11:53:31.517 回答
2

为什么例如网络泛型中重载运算符约束的解决方案对您没有帮助?

于 2009-04-24T11:38:05.063 回答
0

您可以重载运算符,但编译器不知道如何添加两个未知的泛型类型(T + T),并且您无法添加约束,因为运算符是静态成员。

一种方法( .Net 2.0 中的[Edit])是在 Matrix 的静态构造函数中为所有运算符方法创建一个工厂,这将为值类型 T 创建一个正确的实现(基于其 TypeCode,例如例如),或抛出NotImplementedException不支持的值类型。但是这样一来,您就没有编译时检查。

[编辑]在 .Net 3.5 中,您实际上可以使用表达式树获取通用参数的运算符:https ://jonskeet.uk/csharp/miscutil/usage/genericoperators.html 。

您也可以查看此链接:http: //msdn.microsoft.com/en-us/library/system.linq.expressions.binaryexpression.aspx

于 2009-04-24T11:51:34.517 回答