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

前端 未结 6 496
误落风尘
误落风尘 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:24

    It sounds like you want something like:

    Func celsiusToKelvin = x => x + 273.15m;
    Func kelvinToCelsius = x => x - 273.15m;
    Func fahrenheitToKelvin = x => ((x + 459.67m) * 5m) / 9m;
    Func kelvinToFahrenheit = x => ((x * 9m) / 5m) - 459.67m;
    

    However, you might want to consider not just using decimal, but having a type which knows the units so you can't accidentally (say) apply the "Celsius to Kelvin" conversion to a non-Celsius value. Possibly have a look at the F# Units of Measure approach for inspiration.

提交回复
热议问题