我一直在努力學習更多關於代表和lambdas的知識,同時在涉及溫度轉換以及一些烹飪測量轉換(如Imperial到Metric)的小型烹飪項目上工作時,我一直在想辦法制作一個可擴展的單位轉換器。如何爲C#中的度量單位創建通用轉換器?
這是我開始的,以及代碼評論我的一些計劃是什麼。我沒有計劃像下面那樣使用它,我只是測試了C#的一些特性,我不太清楚,我也不確定如何進一步採用它。有沒有人對如何在下面的評論中創建我正在討論的內容有任何建議?由於
namespace TemperatureConverter
{
class Program
{
static void Main(string[] args)
{
// Fahrenheit to Celsius : [°C] = ([°F] − 32) × 5⁄9
var CelsiusResult = Converter.Convert(11M,Converter.FahrenheitToCelsius);
// Celsius to Fahrenheit : [°F] = [°C] × 9⁄5 + 32
var FahrenheitResult = Converter.Convert(11M, Converter.CelsiusToFahrenheit);
Console.WriteLine("Fahrenheit to Celsius : " + CelsiusResult);
Console.WriteLine("Celsius to Fahrenheit : " + FahrenheitResult);
Console.ReadLine();
// If I wanted to add another unit of temperature i.e. Kelvin
// then I would need calculations for Kelvin to Celsius, Celsius to Kelvin, Kelvin to Fahrenheit, Fahrenheit to Kelvin
// Celsius to Kelvin : [K] = [°C] + 273.15
// Kelvin to Celsius : [°C] = [K] − 273.15
// Fahrenheit to Kelvin : [K] = ([°F] + 459.67) × 5⁄9
// Kelvin to Fahrenheit : [°F] = [K] × 9⁄5 − 459.67
// The plan is to have the converters with a single purpose to convert to
//one particular unit type e.g. Celsius and create separate unit converters
//that contain a list of calculations that take one specified unit type and then convert to their particular unit type, in this example its Celsius.
}
}
// at the moment this is a static class but I am looking to turn this into an interface or abstract class
// so that whatever implements this interface would be supplied with a list of generic deligate conversions
// that it can invoke and you can extend by adding more when required.
public static class Converter
{
public static Func<decimal, decimal> CelsiusToFahrenheit = x => (x * (9M/5M)) + 32M;
public static Func<decimal, decimal> FahrenheitToCelsius = x => (x - 32M) * (5M/9M);
public static decimal Convert(decimal valueToConvert, Func<decimal, decimal> conversion) {
return conversion.Invoke(valueToConvert);
}
}
}
更新:試圖澄清我的問題:
使用以下只是我的溫度例子,我將如何創建一個包含拉姆達轉換的列表,以攝氏一類你再傳遞一個給定的溫度,它會嘗試將其轉換成攝氏(如果計算是可用的)
實施例的僞代碼:
enum Temperature
{
Celcius,
Fahrenheit,
Kelvin
}
UnitConverter CelsiusConverter = new UnitConverter(Temperature.Celsius);
CelsiusConverter.AddCalc("FahrenheitToCelsius", lambda here);
CelsiusConverter.Convert(Temperature.Fahrenheit, 11);
單位在F#被支持,我認爲它可以是一個很好[特徵](https://github.com/dotnet/roslyn/issues/144)爲C# vNext。現在我發現這個項目[QuantityTypes](https://github.com/objorke/QuantityTypes),它實現了C#中的度量單位。 – orad