如何正确写INT,双,浮法,数学等扩展方法? [英] How do I properly write Math extension methods for int, double, float, etc.?

查看:119
本文介绍了如何正确写INT,双,浮法,数学等扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一系列的扩展方法来简化数学运算。例如:

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

而不是

Math.Pow(2, 5)

我希望能够写

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?

谢谢!

推荐答案

不幸的是,我认为你被卡住这三个实现。获得多种类型的方法摆脱单一定义的唯一方法是使用泛型,但它是不可能的编写能够做一些专门为数字类型有用的泛型方法。

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.

这篇关于如何正确写INT,双,浮法,数学等扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆