2009-06-07 69 views
5

我想編寫一系列擴展方法來簡化數學運算。例如:如何正確編寫int,double,float等數學擴展方法?

而不是

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

還是有一個絕招,以允許任何數值類型單一的擴展方法的工作?

謝謝!

+3

對於INumeric的另一投票 – Robert 2009-06-07 04:10:28

+0

+1是的,我很驚訝,這不是框架的一部分開始。 – Pwninstein 2009-06-07 14:16:53

回答

2

不幸的是我認爲你堅持三個實現。從單個定義中獲取多個類型化方法的唯一方法是使用泛型,但不可能編寫一個通用的方法,該方法可以專門爲數字類型執行一些有用的操作。

0

你只需要重寫十進制和雙在這個問題指出:here

0

一個解決方案,我用的是使分機上目的。這使得這成爲可能,但不幸的是它會在所有對象上可見。

public static double Power(this object number, double power) 
{ 
    return Math.Pow((double) number, power); 
}