예제 #1
0
        public static double Convert(double number, string fromUnit, string toUnit)
        {
            lock (_syncRoot)
            {
                if (!_initialized)
                {
                    Init();
                }
            }
            // special case for temperatures which has to be converted with a function in some cases
            if (TemperatureConverter.IsTempMapping(fromUnit, toUnit))
            {
                return(TemperatureConverter.Conversions[$"{fromUnit}>{toUnit}"](number));
            }

            if (!IsValidUnit(fromUnit))
            {
                throw new ArgumentException("Invalid fromUnit", fromUnit);
            }
            if (!IsValidUnit(toUnit))
            {
                throw new ArgumentException("Invalid toUnit", toUnit);
            }
            var from = _conversions[fromUnit];
            var to   = _conversions[toUnit];

            if (from.UnitType != to.UnitType)
            {
                throw new ArgumentException("Units are not compatible: " + fromUnit + " and " + toUnit);
            }
            return(number * (from.Value / to.Value));
        }
예제 #2
0
 public static bool IsValidUnit(string unit)
 {
     lock (_syncRoot)
     {
         if (!_initialized)
         {
             Init();
         }
     }
     if (!_conversions.ContainsKey(unit) && !TemperatureConverter.IsValidUnit(unit))
     {
         return(false);
     }
     return(true);
 }