TK.*_*TK. 4 c# units-of-measurement data-structures
我有一个C#应用程序,我需要在3个不同的单位之间进行转换(例如:升,加仑和品脱).
该应用程序需要知道一定量的液体,比如:1品脱,10品脱,20品脱和100品脱.我打算进行计算并对值进行硬编码(不理想但必要),
我正在寻找一种数据结构,可以让我轻松地从一个单元转换到另一个单元.
有什么建议?
请注意:我实际上并没有使用大量的液体,这只是一个例子!
您可以在其中存储转换因子矩阵
你有(不准确,但假设有两品脱一升和4升加仑)
a b c
a 1 2 0.25
b 0.5 1 0.125
c 4 8 1
Run Code Online (Sandbox Code Playgroud)
或者,您可以决定在转换为其他类型之前将所有内容都转换为基值(升),然后您只需要第一行.
将此包装在一个方法中,该方法需要多个单位,"from"类型和"two"类型用于转换.
希望这可以帮助
编辑:根据要求编写一些代码
public enum VolumeType
{
Litre = 0,
Pint = 1,
Gallon = 2
}
public static double ConvertUnits(int units, VolumeType from, VolumeType to)
{
double[][] factor =
{
new double[] {1, 2, 0.25},
new double[] {0.5, 1, 0.125},
new double[] {4, 8, 1}
};
return units * factor[(int)from][(int)to];
}
public static void ShowConversion(int oldUnits, VolumeType from, VolumeType to)
{
double newUnits = ConvertUnits(oldUnits, from, to);
Console.WriteLine("{0} {1} = {2} {3}", oldUnits, from.ToString(), newUnits, to.ToString());
}
static void Main(string[] args)
{
ShowConversion(1, VolumeType.Litre, VolumeType.Litre); // = 1
ShowConversion(1, VolumeType.Litre, VolumeType.Pint); // = 2
ShowConversion(1, VolumeType.Litre, VolumeType.Gallon); // = 4
ShowConversion(1, VolumeType.Pint, VolumeType.Pint); // = 1
ShowConversion(1, VolumeType.Pint, VolumeType.Litre); // = 0.5
ShowConversion(1, VolumeType.Pint, VolumeType.Gallon); // = 0.125
ShowConversion(1, VolumeType.Gallon, VolumeType.Gallon);// = 1
ShowConversion(1, VolumeType.Gallon, VolumeType.Pint); // = 8
ShowConversion(1, VolumeType.Gallon, VolumeType.Litre); // = 4
ShowConversion(10, VolumeType.Litre, VolumeType.Pint); // = 20
ShowConversion(20, VolumeType.Gallon, VolumeType.Pint); // = 160
}
Run Code Online (Sandbox Code Playgroud)
我通过提供正确的访问方法(属性)以其他语言完成此操作:
for the class Volume:
AsLitre
AsGallon
AsPint
for the class Distance:
AsInch
AsMeter
AsYard
AsMile
Run Code Online (Sandbox Code Playgroud)
另一个优点是内部格式无关紧要.
| 归档时间: |
|
| 查看次数: |
5971 次 |
| 最近记录: |