How do I create a generic converter for units of measurement in C#?

前端 未结 6 618
误落风尘
误落风尘 2021-01-31 06:48

I have been trying to learn a bit more about delegates and lambdas while working on a small cooking project that involves temperature conversion as well as some cooking measurem

6条回答
  •  情书的邮戳
    2021-01-31 07:06

    One can define a physical units generic type such that, if one has for each unit a type which implements new and includes a translation method between that unit and a "base unit" of that type, one can perform arithmetic on values that are expressed in different units and have them converted as necessary, using the type system such that a variable of type AreaUnit would only accept things dimensioned in square inches, but if one said myAreaInSquareInches= AreaUnit.Product(someLengthInCentimeters, someLengthInFathoms); it would automatically translate those other unit before performing the multiplication. It can actually work out pretty well when using method-call syntax since methods like Product(T1 p1, T2 p2) method can accept generic type parameters their operands. Unfortunately, there's no way to make operators generic, nor is there way for a type like AreaUnit where T:LengthUnitDescriptor to define a means of conversion to or from some other arbitrary generic type AreaUnit. An AreaUnit could define conversions to and from e.g. AreaUnit, but there's no way the compiler could be told that code which is given an AreaUnit and wantsAreaUnit` can convert inches to angstroms and then to centimeters.

提交回复
热议问题