根据通用结果“T”寻找更简洁/更好的强制“num”类型的方法。 例如:
int iCartesianAngleInDegrees=45, _iDistanceBetween=85;
Vector<int> ivectXY=new Vector<int>(10,30);
ivectXY.moveByDegreesAndDistance(iCartesianAngleInDegrees, _iDistanceBetween);
在moveByDegreesAndDistance方法中,我的kludge检查runtimeType以调用toInt或toDouble。这对我来说似乎不合适。有什么建议/提示赞赏吗?
class Vector<T extends num> extends Coordinate<T> {
...
/**
* Advance x/y in Direction(Cartesian Degrees) for a given Distance
* TODO:PerfTest
**/
Vector<T> moveByDegreesAndDistance(T iDegrees, T iDistance) {
//cartesianToCompass(135) = 225
double _dblAngleInRadians = degreesToRadians(iDegrees),
_dblX = iDistance * math.cos(_dblAngleInRadians),
_dblY = iDistance * math.sin(_dblAngleInRadians);
//This will not automatically coerce type
// x += _dblX as T;
// y += _dblY as T;
if (_dblX is T) {
x += _dblX;
y += _dblY;
} else {
if (x.runtimeType == int) {
x += _dblX.toInt();
y += _dblY.toInt();
} else {
x += _dblX.toDouble();
y += _dblY.toDouble();
}
}
return this;
}
}
答案 0 :(得分:1)
_dblAngleInRadians
,_dblX
,_dblY
为double
您只需测试iDegrees
是int
并使用toInt()在这种情况下。
class Vector<T extends num> extends Coordinate<T> {
...
/**
* Advance x/y in Direction(Cartesian Degrees) for a given Distance
* TODO:PerfTest
**/
Vector<T> moveByDegreesAndDistance(T iDegrees, T iDistance) {
//cartesianToCompass(135) = 225
double _dblAngleInRadians = degreesToRadians(iDegrees),
_dblX = iDistance * math.cos(_dblAngleInRadians),
_dblY = iDistance * math.sin(_dblAngleInRadians);
//This will not automatically coerce type
// x += _dblX as T;
// y += _dblY as T;
final isInt = iDegrees is int;
x += isInt ? _dblX.toInt() : _dblX;
y += isInt ? _dblY.toInt() : _dblY;
return this;
}