目前有一简单需求,制作一个单位转换小工具,采用C# winform,比如长度单位换算,m转cm,m转dm。温度单位换算,摄氏度华氏度等等。因为每个单位转换之间都是双向的,且是多对多的关系,数据结构应该如何设计呢?目前能想到的设计一个类,一个类对应一个单位和其他单位之间的换算关系,如下,
public class FuncUnit
{
public string baseUnit { get; set; } //基础单位
public Dictionary<string, Func<double, double>> otherUnitMap = null; //其他范围与期出单位之间的换算关系
}
把所有单位的换算关系都存储再List list 里面,如温度,
temperatureUnitList.Add(new FuncUnit()
{
baseUnit = "°C",
otherUnitMap = new Dictionary<string, Func<double, double>>() {
{ "°K", v => v + 273.15},
{ "°f", v => 1.8 * v + 32},
{"°R", v => (v + 273.15) * 1.8 }
}
});
temperatureUnitList.Add(new FuncUnit()
{
baseUnit = "°K",
otherUnitMap = new Dictionary<string, Func<double, double>>() {
{ "°C", v => v - 273.15},
{ "°f", v => 1.8 * (v - 273.15) + 32},
{"°R", v => (v - 273.15 + 273.15) * 1.8 }
}
});
temperatureUnitList.Add(new FuncUnit()
{
baseUnit = "°f",
otherUnitMap = new Dictionary<string, Func<double, double>>() {
{ "°C", v => (v - 32) / 1.8},
{ "°K", v => (v - 32)/1.8 + 273.15},
{"°R", v => v - 32 + 1.8 * 273.15 }
}
});
temperatureUnitList.Add(new FuncUnit()
{
baseUnit = "°R",
otherUnitMap = new Dictionary<string, Func<double, double>>() {
{ "°C", v => v/1.8 - 273.15},
{ "°K", v => v/1.8},
{"°f", v => v-1.8*273.15+32}
}
});
计算时候的代码,
Dictionary<string,Func<double,double>> map = list.Find(v => v.baseUnit.Equals(from)).otherUnitMap;
return map[to](value);
温度只填写了四个单位之间的相互换算关系,但是之间的换算有重复,感觉这样做重复代码比较多,感觉不太合理,请教大家是否还有其他更方便的办法呢?十分感谢!