如何为int,double,float等正确编写Math扩展方法?

Mar*_*ter 5 c# extension-methods

我想编写一系列Extension方法来简化数学运算.例如:

代替

Math.Pow(2, 5)
Run Code Online (Sandbox Code Playgroud)

我希望能够写作

2.Power(5) 
Run Code Online (Sandbox Code Playgroud)

这是(在我看来)更清楚.

问题是:在编写扩展方法时如何处理不同的数字类型?我是否需要为每种类型编写扩展方法:

public static double Power(this double number, double power) {
    return Math.Pow(number, power);
}
public static double Power(this int number, double power) {
    return Math.Pow(number, power);
}
public static double Power(this float number, double power) {
    return Math.Pow(number, power);
}
Run Code Online (Sandbox Code Playgroud)

或者有一个技巧允许单个扩展方法适用于任何数字类型?

谢谢!

jer*_*jvl 2

不幸的是,我认为您被困在这三种实现中。从单个定义中获取多个类型化方法的唯一方法是使用泛型,但不可能编写一个泛型方法来专门对数字类型执行有用的操作。