Вы хотите Func<double, double>
вместо Action
;Дано double
(например, 4.5
Вольт) возврата double
.
x => x / 1000
Напротив, Action
не принимает аргументов и ничего не возвращает: () => {...}
Код:
// Let's implement immutable class (assigned once, never change)
// in order to prevent occasional errors like device.Name = ...
private class Device {
public string Name { get; }
public Func<double, double> Conversion { get; }
public string Unit { get; }
// Let's validate the input (at least, for null)
public Device(string name, Func<double, double> conversion, string unit) {
if (null == name)
throw new ArgumentNullException(nameof(name));
else if (null == conversion)
throw new ArgumentNullException(nameof(conversion));
else if (null == unit)
throw new ArgumentNullException(nameof(unit));
Name = name;
Conversion = conversion;
Unit = unit;
}
}
...
List<Device> deviceList = new List<Device>() {
new Device("battery-voltage", x => x / 1000, "V"),
new Device("air-temperature", x => (175 * x / 65535) - 45, "°C"),
};
Возможное использование:
// What device should we use if we want °C unit?
Device temperature = deviceList
.FirstOrDefault(item => item.Unit == "°C");
byte[] dataToConvert = new byte[] {123, 45, 79};
// Device found
if (temperature != null) {
// Converting: for each value in dataToConvert we obtain corresponding t value
foreach (var value in dataToConvert) {
double t = temperature.Conversion(value);
...
}
}
Или вы можете даже получить массив преобразованных значений (double[]
) с помощью Linq :
byte[] dataToConvert = new byte[] {123, 45, 79};
// Let's throw exception if device has not been found
Device temperature = deviceList
.First(item => item.Unit == "°C");
double[] results = dataToConvert
.Select(v => temperature.Convert(v))
.ToArray();