简体   繁体   English

C# - 是否有数学接口?

[英]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.我想在矩阵中有一个通用类型,你可以用它进行算术运算,因为我想制作一个 class 代表分数而不是使用双精度,但我也想在未来使用双精度。 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.我以为我可以使用类似where T: IMathable东西,但我无法弄清楚它应该有什么 inheirentents。

Have you tried the documents?你试过文件了吗?

There is a Math class, you can check if that's the one you want Math Class有一个 Math class,你可以看看是不是你想要的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.如果这个没有解决,请尝试更具体一些,提及具有您想要的 function 的语言可以帮助我们帮助您。

Yes, in .NET 7 / C# 11:是的,在 .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;
    }
}

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

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