我一直在学习委托和Lambda表达式,同时还在一个小烹饪项目中涉及温度转换以及一些烹饪度量单位的转换,例如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);
}
}
}
更新:尝试澄清我的问题:
以我下面的温度示例为例,如何创建一个类,其中包含一系列将给定温度转换为摄氏度的lambda转换,您可以将该温度传递给它,并尝试将其转换为摄氏度(如果可用计算)
伪代码示例:
enum Temperature
{
Celcius,
Fahrenheit,
Kelvin
}
UnitConverter CelsiusConverter = new UnitConverter(Temperature.Celsius);
CelsiusConverter.AddCalc("FahrenheitToCelsius", lambda here);
CelsiusConverter.Convert(Temperature.Fahrenheit, 11);