【发布时间】:2017-09-29 22:36:11
【问题描述】:
我想写一系列扩展方法来简化数学运算。例如:
代替
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);
}
或者有什么技巧可以让单个扩展方法适用于任何数字类型?
谢谢!
【问题讨论】:
-
+1 是的,我很惊讶这不是框架的一部分。
-
警告 使用此类扩展方法时:
-10.Power(2) == -100。减号应用于10.Power(2)的结果。 -
@HugoRune:有趣的一点!但我确实认为 OP 仍然会使用变量而不是显式值。问题中的硬编码值似乎是一个示例问题,而不是预期用途。
标签: c# extension-methods