I think it's better to create the Unit class for the unit of measure and the Quantity class, which associates the unit of measure with the sum. Take a look at the Quantitative Template for this idea. Since you also want to write the "type" of the unit of measure, you can create a UnitType class that records this information:
public sealed partial class UnitType { public string Name { get; private set; } public UnitType(string name) { Name = name; } } public sealed partial class Unit { public string Name { get; private set; } public UnitType Type { get; private set; } public Unit(string name, UnitType type) { Name = name; Type = type; } }
(You must make them the correct value types by overriding Equals and GetHashCode )
The Unit class can be extended to provide, for example, conversions, compound units, formatting, and parsing.
Then you can define common cases inside classes:
public partial class UnitType { public static readonly UnitType Mass = new UnitType("Mass"); public static readonly UnitType Length = new UnitType("Length"); } public partial class Unit { public static readonly Unit Grams = new Unit("g", UnitType.Mass); public static readonly Unit Kilos = new Unit("kg", UnitType.Mass);
Or define your "hierarchies" with static classes:
public static class Mass { public static readonly UnitType Type = new UnitType("Mass"); public static readonly Unit Grams = new Unit("g", Type); public static readonly Unit Kilos = new Unit("kg", Type); ... } public static class Length ...
The Quantity class will also be an immutable value type (just showing its use):
var eniacWeight = new Quantity(27, Mass.Tons);
Or you can use extension methods to create Quantity s:
var eniacWeight = 27.Tons();
(from ENIAC )
Jordão
source share