简体   繁体   中英

C# - Is there an interface for math?

I was working on a matrix-class, in which i want to make som linear algebra functions. I want to have a generic type in the matrix, which you can do arithmetic operations with, since i want to make a class representing a fraction instead of using double, but i also wanna use double in the future. Like this:

class Temp<T>
    {
        T[,] matrix;
        // Example of a math-using function
        public T Sum()
        {
            T sum = matrix[0,0];
            for(int i = 0; i < matrix.GetLength(0); i++)
            {
                for(int j = 0; j < matrix.GetLength(1); j++)
                {
                    sum += matrix[i, j]; // Error here
                }
            }
            return sum;
        }
    }

I thought that i could use something like where T: IMathable but i couldn't figure out what inheirentents it should have.

Have you tried the documents?

There is a Math class, you can check if that's the one you want Math Class

you import it with

using System;

Please give me a feedback on that. If this one doesn't solve try to be more specific, mentioning the language that has the function you want can help us to help you.

Yes, in .NET 7 / C# 11:

class Temp<T> where T : INumber<T>
{
    T[,] matrix;
    public T Sum()
    {
        T sum = matrix[0, 0];
        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                sum += matrix[i, j];
            }
        }
        return sum;
    }
}

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