有没有一种方法可以为自定义类型重载数学函数?

时间:2018-10-15 15:30:49

标签: c# .net operator-overloading

我知道您可以对自定义类型进行运算符重载(+-* /)。是否也可以对自定义数学函数执行相同的操作?这将使向量运算更加自然(如R)。示例:

vector = [1, 2, 3, 4, 5]

vector + vector = [2, 4, 6, 8, 10]  # can be achieved with operator overloading
vector * 5 = [5, 10, 15, 20, 25] # can be achieved with operator overloading

pow(vector, 2) = [ 1, 4, 9, 16, 25 ]  # is it possible in C#?

更新
从下面的答案中,我看到“函数重载”是不可能的(可能没有太大意义),处理该问题的最佳方法是创建自定义数学函数库(静态类)。
尽管有办法将“自定义函数”与其他自定义类型一起重用,但该解决方案很好。假设我有数字(整数/浮点数),复数,向量和矩阵(向量数组)。我希望我的Pow函数可用于所有4种类型(它应为对象中的每个数字元素提供动力)。
另外,有没有一种方法可以使函数根据输入类型做不同的事情?例如

abs(-1) = 1  # for integer abs just change the sign if negative
abs(4+3i) = sqrt(4^2+3^2) = 5 # smth different for complex number

2 个答案:

答案 0 :(得分:2)

您可以利用C#6中添加的using static功能来实现类似的功能。这使您可以从类中使用静态方法,而不必指定类型名称。 (.NET Math类经常作为此功能的example引用。)

假设一个实现Vector的{​​{1}}类,您可以创建一个包含静态IEnumerable<double>函数的类:

Pow

然后,在您要使用此类的任何代码文件中,包含语句

namespace Vectors
{
    public static class VectorMath
    {
        public static Vector Pow(Vector v, int exponent)
        {
            return new Vector(v.Select(n => Math.Pow(n, exponent)));
        }
    }
}

这将允许您调用using static Vectors.VectorMath; 方法,而无需指定它是Pow类的成员:

VectorMath

答案 1 :(得分:0)

您可以为Array类创建扩展方法pow()

 public static class VecorExtension
{
        public static void pow(this Array vector, int i)
        {
            ...
        }
}

用法:

  

[1,2,3] .pow(2);

Extension methods