如何为int,double,float等正确编写Math扩展方法?
我想编写一系列Extension方法来简化数学运算。 例如:
代替
Math.Pow(2, 5)
我想能写
2.Power(5)
这是(在我看来)更清楚。
问题是:在编写扩展方法时如何处理不同的数字类型? 我是否需要为每种类型编写扩展方法:
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); }
或者是否有一个技巧允许单个扩展方法适用于任何数字类型?
谢谢!
不幸的是,我认为你坚持这三个实现。 从单个定义中获取多个类型化方法的唯一方法是使用generics,但是不可能编写一个通用方法,可以为数字类型做一些有用的事情。
我不认为它可能与C#3.0。 看起来你可以做到C#4.0
http://blogs.msdn.com/lucabol/archive/2009/02/05/simulating-inumeric-with-dynamic-in-c-4-0.aspx
你只需要覆盖这个问题中提到的Decimal和Double: 这里
我使用的一个解决方案是在对象上进行扩展。 这使得这成为可能,但遗憾的是它将在所有对象上可见。
public static double Power(this object number, double power) { return Math.Pow((double) number, power); }