假设我有一个泛型矩阵类型:
class Matrix<T>
{
private T[,] _data;
}
可以重载Matrix<T>
if and only if上的+
运算符T
具有重载的+
运算符吗?
最近我写了很多《铁 rust 》,我希望这能奏效:
class Matrix<T>
{
private T[,] _data;
public static Matrix<T> operator+(Matrix<T> lhs, Matrix<T> rhs)
where T: IAdditionOperators<T>
{
// ...
}
}
遗憾的是,where
只能应用于方法本身的泛型参数,而不能应用于其包含类的泛型参数.
我知道我可以go 掉where
子句,在方法体中使用dynamic
来执行加法,但在我的例子中,performance implications是不能接受的.
This question类似,但可以用C#11中新的IAdditionOperator<T>
接口来解决.但是,我希望我的Matrix<T>
类型也可以与没有加运算符的类型T
一起使用.(不过,如果在运行时选中这一点也没问题.)
也许是有子类和隐式转换的东西?