![](/img/trans.png)
[英]how to convert part of the string to int/float/vector3 etc. without creating a temp string?
[英]How do I properly write Math extension methods for int, double, float, etc.?
我想编写一系列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);
}
或者有一个技巧允许单个扩展方法适用于任何数字类型?
谢谢!
不幸的是,我认为你坚持这三个实现。 从单个定义中获取多个类型化方法的唯一方法是使用泛型,但是不可能编写一个通用方法,可以为数字类型做一些有用的事情。
我使用的一个解决方案是在对象上进行扩展。 这使得这成为可能,但不幸的是它将在所有对象上可见。
public static double Power(this object number, double power)
{
return Math.Pow((double) number, power);
}
你只需要覆盖这个问题中提到的Decimal和Double: 这里
我不认为它可能与C#3.0。 看起来你可以做到C#4.0
http://blogs.msdn.com/lucabol/archive/2009/02/05/simulating-inumeric-with-dynamic-in-c-4-0.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.