【问题标题】:C# - Is there an interface for math?C# - 是否有数学接口?
【发布时间】:2022-12-14 17:39:00
【问题描述】:

我正在研究一个矩阵类,我想在其中制作一些线性代数函数。我想在矩阵中有一个通用类型,你可以用它做算术运算,因为我想创建一个代表分数的类而不是使用双精度,但我也想在未来使用双精度。像这样:

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;
        }
    }

我以为我可以使用类似 where T : IMathable 的东西,但我无法弄清楚它应该具有哪些继承性。

【问题讨论】:

  • Generic Math 已经预览了一段时间,我相信它确实进入了已发布的 .NET 7

标签: generics inheritance c#-3.0


【解决方案1】:

你试过文件了吗?

有一个数学课,你可以看看是不是你想要的Math Class

你导入它

using System;

请给我一个反馈。如果这个没有解决,请尝试更具体,提及您想要的功能可以帮助我们帮助您。

【讨论】:

  • 我想将泛型限制为只能进行算术运算的类型,我看不出 System.Math 对此有何帮助
  • 您可以尝试寻找一个库来解决这个问题,否则您最终将手动完成。
  • 和通用数学接缝来完成它
【解决方案2】:

是的,在 .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;
    }
}

【讨论】:

    猜你喜欢
    • 2012-02-02
    • 2014-09-09
    • 2018-06-30
    • 2013-06-08
    • 2011-08-08
    • 2011-02-16
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    相关资源
    最近更新 更多