How do I properly write Math extension methods for int, double, float, etc.?

荒凉一梦 提交于 2019-12-09 13:09:44

问题


I want to write a series of Extension methods to simplify math operations. For example:

Instead of

Math.Pow(2, 5)

I'd like to be able to write

2.Power(5) 

which is (in my mind) clearer.

The problem is: how do I deal with the different numeric types when writing Extension Methods? Do I need to write an Extension Method for each type:

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

Or is there a trick to allow a single Extension Method work for any numeric type?

Thanks!


回答1:


Unfortunately I think you are stuck with the three implementations. The only way to get multiple typed methods out of a single definition is using generics, but it is not possible to write a generic method that can do something useful specifically for numeric types.




回答2:


One solution I use is to make the extension on object. This makes this possible, but unfortunately it will be visible on all objects.

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



回答3:


I dont think its possible with C# 3.0. Looks like you might be able to do it C# 4.0

http://blogs.msdn.com/lucabol/archive/2009/02/05/simulating-inumeric-with-dynamic-in-c-4-0.aspx




回答4:


You only need to override Decimal and Double as is noted in this question: here



来源:https://stackoverflow.com/questions/961038/how-do-i-properly-write-math-extension-methods-for-int-double-float-etc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!