假设我有
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 { ... }
}
避免装箱或复制 struct
。
它运行良好,一切正常,但是否有任何我不知道的缺点(除了内存使用量的微不足道的增加外)?这是一种公认的做法,还是出于我可能不知道的任何原因不鼓励这样做?
最佳答案
泛型的成本很小,主要是代码量较大。 recent blog post from Joe Duffy对此进行了相当详细的介绍。但是,总的来说,避免对频繁调用的代码进行装箱是一件好事,并且可能值得生成更多的字节代码(实际上,这意味着内存使用量略高,JIT 的工作量更大)。
关于c# - 使用受约束的泛型而不是接口(interface)——缺点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8370792/