gpt4 book ai didi

dart - 如何在double和int之间强制转换num类型

转载 作者:行者123 更新时间:2023-12-03 03:47:00 25 4
gpt4 key购买 nike

寻找一种基于通用结果“T”的强制性更好的方式来强制“num”类型。
例:

int iCartesianAngleInDegrees=45, _iDistanceBetween=85;
Vector<int> ivectXY=new Vector<int>(10,30);
ivectXY.moveByDegreesAndDistance(iCartesianAngleInDegrees, _iDistanceBetween);

在moveByDegreesAndDistance方法中,我的合并检查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;
}

}

最佳答案

_dblAngleInRadians_dblX_dblYdouble,您只需要测试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;
}

关于dart - 如何在double和int之间强制转换num类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22515815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com