private void ParseUnit <T>(List <T> units, eLeafType eChildLeaf) { string name = ""; foreach (T unit in units) { if (eChildLeaf == eLeafType.UNIT) { BaseUnit baseUnit = (BaseUnit)Convert.ChangeType(unit, typeof(BaseUnit)); name = baseUnit.name; } else { DerivedUnit derivedUnit = (DerivedUnit)Convert.ChangeType(unit, typeof(DerivedUnit)); name = derivedUnit.name; } int pos = part.LastIndexOf(name); if (pos < 0) { continue; } children.Add(new Leaf(eOperatorType.NONE, eLeafType.PREFIX, part.Substring(0, pos))); if (ErrorCheck(true, 1)) { continue; } children.Add(new Leaf(eOperatorType.NONE, eLeafType.POWER, part.Substring(pos + name.Length))); if (ErrorCheck(true, 2)) { continue; } children.Add(new Leaf(eOperatorType.MULTIPLY, eChildLeaf, name)); if (ErrorCheck(true, 3)) { continue; } if (children.Count == 6) { if (pos == 0) { for (int i = 0; i < 3; i++) { children.RemoveAt(0); } break; } else { for (int i = 0; i < 3; i++) { children.RemoveAt(children.Count - 1); } } } else if (pos == 0) { break; } } }
private void Parse() { //Trim any start and end bits part = Trim(rawPart); //Empty part is default values if (part == "") { if (eLeaf == eLeafType.UNIT) { value = 1; //A null unit for a pure number value } return; } switch (eLeaf) { case eLeafType.PREFIX: ParsePrefix(part); break; case eLeafType.POWER: if (double.TryParse(part, out leafResult.power)) { break; } UnitSystem.Errors.Add("Power could not be found : " + part); break; case eLeafType.UNIT: foreach (BaseUnit unit in UnitSystem.BaseUnits) { if (part == unit.name) { leafResult.dimensions[unit.dimension] = 1; baseUnit = unit; value = 1; return; } } UnitSystem.Errors.Add("Base unit could not be found : " + part); break; case eLeafType.DERIVEDUNIT: foreach (DerivedUnit unit in UnitSystem.DerivedUnits) { if (part == unit.name) { children.Add(new Leaf(eOperatorType.MULTIPLY, eLeafType.COMPOUND, unit.baseUnits)); if (ErrorCheck(false, 1)) { continue; } derivedUnit = unit; UpdateCompound(); return; } } UnitSystem.Errors.Add("Derived unit could not be found : " + part); break; case eLeafType.COMPOUND: //Split operators SplitOperators(); if (children.Count > 0) { UpdateCompound(); break; } //Parse a possible derived unit ParseUnit(UnitSystem.DerivedUnits, eLeafType.DERIVEDUNIT); if (children.Count == 3) { UpdateValue(); break; } //Parse a possible base unit ParseUnit(UnitSystem.BaseUnits, eLeafType.UNIT); if (children.Count == 3) { UpdateValue(); break; } //Parse a pure number children.Add(new Leaf(eOperatorType.NONE, eLeafType.PREFIX, part)); children.Add(new Leaf(eOperatorType.NONE, eLeafType.POWER, "")); children.Add(new Leaf(eOperatorType.MULTIPLY, eLeafType.UNIT, "")); UpdateValue(); if (UnitSystem.Errors.Count > 0) { UnitSystem.Errors.Add("Unit could not be found : " + part); } break; } }