使用约束泛型而不是接口 - 缺点?

Meh*_*dad 8 c# generics boxing interface constraints

让我说我有

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 { ... } }
}
Run Code Online (Sandbox Code Playgroud)

有时候,而不仅仅是说

static class Matrices {
    static IMatrix Multiply(IMatrix a, IMatrix b) { ... }
}
Run Code Online (Sandbox Code Playgroud)

我最终做了

static class Matrices {
    static IMatrix Multiply<T1, T2>(T1 a, T2 b)
        where T1 : IMatrix
        where T2 : IMatrix { ... }
}
Run Code Online (Sandbox Code Playgroud)

或者甚至是

static class Matrices {
    static IMatrix Multiply<T1, T2>([In] ref T1 a, [In] ref T2 b)
        where T1 : IMatrix
        where T2 : IMatrix { ... }
}
Run Code Online (Sandbox Code Playgroud)

避免拳击或复制structs.

它工作正常,但是有什么缺点我不知道(除了可忽略不计的内存使用量增加)?这是一种公认​​的做法,还是因为我可能不知道的任何原因而气馁?

bob*_*mcr 4

泛型的成本很小,主要是围绕较大的代码大小。Joe Duffy 最近发表的一篇博客文章对此进行了相当详细的介绍。然而,一般来说,避免对频繁调用的代码进行装箱是一件好事,并且可能值得生成更多字节代码(实际上,这意味着稍微更高的内存使用量和 JIT 的更多工作)。