假设我有
interface IMatrix {
double this[int r, int c] { get; }
}
struct Matrix2x2 : IMatrix {
double a1, a2, b1, b2;
double this[int r, int c] { get { ... } }
}
struct Matrix3x3 : IMatrix {
double a1, a2, a3, b1, b2, b3, c1, c2, c3;
double this[int r, int c] { get { ... } }
}
class Matrix : IMatrix { // Any size
double[,] cells;
double this[int r, int c] { get { ... } }
}
有时候,我们不仅需要说出来:
static class Matrices {
static IMatrix Multiply(IMatrix a, IMatrix b) { ... }
}
我最终做了
static class Matrices {
static IMatrix Multiply<T1, T2>(T1 a, T2 b)
where T1 : IMatrix
where T2 : IMatrix { ... }
}
或者甚至更多。
static class Matrices {
static IMatrix Multiply<T1, T2>([In] ref T1 a, [In] ref T2 b)
where T1 : IMatrix
where T2 : IMatrix { ... }
}
为避免结构体的装箱或复制。
这种方法运行良好,但是否存在我不知道的任何缺点(除了内存使用量的微不足道的增加)?这是一种被接受的做法,还是因为某些原因而被反对,我可能没有意识到?