简体   繁体   中英

Type constraint for C# class

I am trying to write a matrix class in C#, and want to cover just integral types. 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. 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.

You won't be able to simply restrict to Int32, or any of these primitive numeric types.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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