简体   繁体   English

C#类的类型约束

[英]Type constraint for C# class

I am trying to write a matrix class in C#, and want to cover just integral types. 我试图用C#编写一个矩阵类,并且只想覆盖整数类型。 Yes, I know, there are probably a bunch of other libraries out there that provide this functionality already - I just wanted to give it a try myself to apply some of the math I'm learning in school. 是的,我知道,可能已经有很多其他库提供了此功能-我只是想尝试一下自己应用在学校学习的一些数学。

Anyway, the real problem here: I have my constructor: 无论如何,真正的问题在这里:我有我的构造函数:

public class Matrix {
    private int[,]    __matrix;

    Matrix(int rows, int columns) {
        /* ... some logic here ... */
        __matrix = new int[row , columns];
    }
}

I know you can constrain to just structs, but that also means that things like DateTime could end up in the matrix. 我知道您可以只约束结构,但这也意味着DateTime东西可能会出现在矩阵中。 Any suggestions on how to solve this, or has anyone seen this done elsewhere? 关于如何解决此问题的任何建议,还是有人在其他地方看到过此建议? I was thinking of writing a generic class, but I'm almost leaning on an attribute that declares allowable types, and then just checking that attribute in code at this point, but am also not at all stoked about the prospect of the boxing/unboxing overhead of using an object[] for my matrix. 我当时在考虑编写一个通用类,但我几乎要依靠声明允许类型的属性,然后在此时检查代码中的该属性,但对装箱/拆箱的前景一无所知使用object[]作为矩阵的开销。

You won't be able to simply restrict to Int32, or any of these primitive numeric types. 您将无法简单地将限制限于Int32或任何这些原始数字类型。

Take a look at this question: Is there a constraint that restricts my generic method to numeric types? 看一下这个问题: 是否存在将我的通用方法限制为数字类型的约束?

The workaround seems way more complicated than we would expect. 解决方法似乎比我们预期的要复杂得多。 Deferring arithmetic operations to some other generic class... 将算术运算推迟到其他通用类...

Read on for more details. 请阅读以获得更多详情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM