您可以将转换因子矩阵存储在哪里
你有(不准确,但假设一升有两品脱,一加仑有 4 升)
a b c
a 1 2 0.25
b 0.5 1 0.125
c 4 8 1
或者,您可以决定在转换为另一种类型之前将所有内容转换为基值(升),然后您只需要第一行。
将此包装在一个方法中,该方法采用多个单位和“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
}