Exemple #1
0
        /// <summary>
        /// Tries to parse a string as a <see cref="MeasureUnit"/> and registers it in this context
        /// on success.
        /// </summary>
        /// <param name="s">The string to parse. Must not be null.</param>
        /// <param name="u">On success, the unit of measure.</param>
        /// <returns>True on success, false if the string can not be parsed as a measur of unit.</returns>
        public bool TryParse(string s, out MeasureUnit u)
        {
            if (s == null)
            {
                throw new ArgumentNullException(nameof(s));
            }
            // 1 - Normalize input by removing all white spaces.
            // Trust the Regex cache for this quite common one.
            s = Regex.Replace(s, "\\s+", String.Empty);
            if (_allUnits.TryGetValue(s, out u))
            {
                return(true);
            }
            Match match = _rUnit.Match(s);

            if (!match.Success)
            {
                return(false);
            }
            var all = new List <ExponentMeasureUnit>();

            do
            {
                if (!TryParseExponent(match, out var e))
                {
                    return(false);
                }
                if (e != MeasureUnit.None)
                {
                    all.Add(e);
                }
                match = match.NextMatch();
            }while(match.Success);
            u = MeasureUnit.Combinator.Create(this, all);
            return(true);
        }
 /// <summary>
 /// Tries to parse a string in the default context (<see cref="StandardMeasureContext.Default"/>).
 /// </summary>
 /// <param name="text">The text to parse.</param>
 /// <param name="u">The resulting measure unit.</param>
 /// <returns>True on success, false otherwise.</returns>
 public static bool TryParse(string text, out MeasureUnit u) => StandardMeasureContext.Default.TryParse(text, out u);
 /// <summary>
 /// Initializes a new <see cref="Quantity"/>.
 /// </summary>
 /// <param name="v">Quantity value.</param>
 /// <param name="unit">Unit of measure. Can be null (<see cref="MeasureUnit.None"/> is used).</param>
 public Quantity(double v, MeasureUnit unit)
 {
     Value       = v;
     _unit       = unit ?? MeasureUnit.None;
     _normalized = null;
 }
Exemple #4
0
 /// <summary>
 /// Constructs a new <see cref="Quantity"/> from a double.
 /// </summary>
 /// <param name="this">This double.</param>
 /// <param name="u">The unit of the measure of the quantity.</param>
 /// <returns>The quantity.</returns>
 public static Quantity WithUnit(this double @this, MeasureUnit u) => new Quantity(@this, u);
 void ThrowArgumentException(MeasureUnit m, string explain)
 {
     throw new ArgumentException($"Already existing unit registration (context '{Name}') for '{m.ToString()}': " + explain);
 }