我想为食物测量实现一个简单的单位转换库,即杯子茶匙。捏,毫升,盎司,升,克,磅等等等。有没有我可以使用的库,如果没有,我想以下面的伪方式滚动我自己的:
enum Unit
{
Centimeters = 0,
Meter = 1,
Kilometer = 2
}
//| | | 0 | 1 | 2 |
//----------------------------------------------
//| | |Centimeters| Meters| Kilometers|
//----------------------------------------------
//|0|Centimeters|1 | 0.01 | 0.000001 |
//----------------------------------------------
//|1|Meters |100 | 1 | 1000 |
//----------------------------------------------
//|2|Kilometers |100000 | 1000 | 1 |
//----------------------------------------------
public float Convert(Unit UnitFrom, Unit UnitTo, UnitValue)
{
float factor = UnitMatrix[UnitFrom][Unit UnitTo];
return UnitValue * factor;
}
//Usage
Convert(Unit.Kilometers, Unit.Meters, 5)
// Lookup factor in this case would be the one at [2, 1] i.e. 1000 so output is 5000
指针,陷阱,太天真了?任何帮助都会很有用。我可以研究的当前开源实现也会很棒。TIA