c# - 使用受约束的泛型而不是接口(interface)——缺点?

标签 c# generics interface constraints boxing

假设我有

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/

相关文章:

c# - 拦截动态调用以避免 RuntimeBinderException

c# - 尝试在执行长进程时添加请等待弹出窗口,弹出窗口显示,但进程从未运行

java - 使用 gson 反序列化时将 TypeToken 转换为 Type 时出错

c# - 通过界面搜索列表

objective-c - 了解在@interface 声明中使用 "(Private)"

c# - HtmlAgilityPack 并选择节点和子节点

c# - 如何创建元组数组?

generics - 快速通用函数中的位移位

c# - 使用 FakeItEasy 伪造泛型方法而不指定类型

oop - 接口(interface)中的 void 方法是代码气味吗?