代码之家  ›  专栏  ›  技术社区  ›  Robin

这可能吗?只要定义了+操作,就可以指定任何泛型类型

  •  1
  • Robin  · 技术社区  · 4 年前

    我不确定这是否可能,但如果可能的话,它将是有用的。

    我试图在一个名为 Matrix<T> . 其目的是能够拥有各种数据类型的矩阵,例如整数、浮点、双精度等。

    现在我想定义加法:

        public static Matrix<T> operator +(Matrix<T> first, Matrix<T> second)
        {
            if (first.dimension != second.dimension)
            {
                throw new Exception("The matrices' dimensions do not match");
            }
            Matrix<T> add = new Matrix<T>(first.dimension);
    
            for (int i = 1; i <= first.rows; i++)
            {
                for (int j = 1; j <= first.columns; i++)
                {
                    add[i,j] = first[i,j] + second[i,j];
                }
            }
            return add;
        }
    

    add[i,j] = first[i,j] + second[i,j]; + 未在类型为的常规对象上定义 T .

    是一种定义了加法的类型。所以,我可以做一个矩阵 int s float s double int[] + 未为定义 s

    因此,与其写作 T + int s、 矩阵 浮动

    编辑:我不知道该怎么办 the linked question from closure 与此相关-我看不到关于操作员的任何信息。如果它们是相关的,有人能解释一下是怎么回事吗?

    1 回复  |  直到 4 年前
        1
  •  1
  •   Guru Stron    4 年前

    目前这是不可能的(至少在不损失编译时安全性或更改API的情况下),但要启用预览功能并 System.Runtime.Experimental 你可以使用的nuget IAdditionOperators 限制 T + 运算符定义。我想说的是,将此接口添加到 Matrix 这本身就是个好主意:

    class Matrix<T> : IAdditionOperators<Matrix<T>, Matrix<T>, Matrix<T>> where T : IAdditionOperators<T, T, T>
    {
       public static Matrix<T> operator +(Matrix<T> left, Matrix<T> right)
        {
            // swap to real implementation here
            T x = default;
            T y = default;
            Console.WriteLine(x + y);
            return default;
        }
    }
    

    另见: