为类的所有属性构建表达式

时间:2019-08-21 07:41:56

标签: c# lambda expression

Expression经验不足,并且很难理解大局。

我有一个定义大量属性的类。 我没有做很多愚蠢的工作,而是尝试使用反射/表达式为我评估这些属性。

该课程的简短示例:

[Function(Name = "sensors")]
internal class Sensors
{
    [CabinetDoubleSensor(SensorType = SensorType.Temperature, Precision = 3)]
    [JsonProperty(PropertyName = "IO_PCW_FL_SPR")]
    public JsonSensor<double> IOPcwFlSpr { get; set; } = new JsonSensor<double>();

    [CabinetDoubleSensor(SensorType = SensorType.Temperature, Precision = 3)]
    [JsonProperty(PropertyName = "IO_PCW_RL_SPR")]
    public JsonSensor<double> IOPcwRlSpr { get; set; } = new JsonSensor<double>();

    // 100+ sensor definitions below
}

我想评估所有属性并将它们存储在列表中,如下所示:

    public IEnumerable<ISensor> UpdateSensors(Json.Sensors jsonUpdate)
    {
        // To test if it works, but clearly, I do NOT want to list all sensor evaluations here!
        UpdateSensor(() => jsonUpdate.IOPcwFlSpr);

        return SensorMap.Values.ToList();
    }

    private void UpdateSensor(Expression<Func<JsonSensor<double>>> propertySelector)
    {
        if (propertySelector.Body is MemberExpression expression)
        {
            var compiledExpression = propertySelector.Compile();
            var jsonSensor = compiledExpression.Invoke();

            var name = expression.Member.Name;
            var cabinetSensor = SensorMap[name];
            cabinetSensor.Value = jsonSensor.Value.ToString($"F{cabinetSensor.Precision}");
        }
    }

那么我被卡住的部分。如前所述,我不想拨打UpdateSensor(() => jsonUpdate.SensorName 100次以上。因此,我正在尝试寻找一种自己构造lambda表达式的方法。

    private static readonly List<PropertyInfo> Properties;

    static SensorFactory()
    {
        Properties = typeof(Json.Sensors).GetProperties().ToList();
    }

    public IEnumerable<ISensor> Test(Json.Sensors jsonUpdate)
    {
        foreach (var property in Properties)
        {
            var getterMethodInfo = property.GetGetMethod();
            var parameterExpression = Expression.Parameter(jsonUpdate.GetType());
            var getterCall = Expression.Call(parameterExpression, getterMethodInfo);

            UnaryExpression castToObject = Expression.Convert(getterCall, typeof(JsonSensor<double>));
            var lambda = (Expression<Func<JsonSensor<double>>>)Expression.Lambda(castToObject, parameterExpression);

            UpdateSensor(lambda);
        }

        // not relevant
        return null;
    }

演员表是非法的:

  

System.InvalidCastException:'无法转换类型的对象   'System.Linq.Expressions.Expression 1[System.Func 2 [Asml.Mbi.FlowAndTemperature.Peripherals.Cabinet.Json.Sensors,Asml.Mbi.FlowAndTemperature.Peripherals.Cabinet.Json.JsonSensor 1[System.Double]]]' to type 'System.Linq.Expressions.Expression 1 [System .Func 1[Asml.Mbi.FlowAndTemperature.Peripherals.Cabinet.Json.JsonSensor 1 [System.Double]]]'”。'

我认为(/希望)我已经接近了,但是我不知道如何获得Expression<Func<JsonSensor<double>>>作为返回值。

1 个答案:

答案 0 :(得分:1)

实际上,您的代码中几乎没有问题。

引发异常本身,因为您为Lambda方法提供了一个参数,这样它就会产生Func<T1, T2>Func<T>不接受任何参数,因此您应该调用Expression.Lambda(castToObject)

无论如何,您可能应该将其更改为Func<Sensors, JsonSensor<double>>,否则需要将jsonUpdate包装为lambda常量。

以下是调整后的UpdateSensorTest方法的示例:

private static void UpdateSensor(Sensors jsonUpdate, Expression<Func<Sensors, JsonSensor<double>>> propertySelector)
{
    if (propertySelector.Body is MemberExpression expression)
    {
        var compiledExpression = propertySelector.Compile();
        // Signature was changed and jsonUpdate is not compiled into lambda; we need to pass reference
        var jsonSensor = compiledExpression.Invoke(jsonUpdate);

        var name = expression.Member.Name;
        var cabinetSensor = SensorMap[name];
        cabinetSensor.Value = jsonSensor.Value.ToString($"F{cabinetSensor.Precision}");
    }
}

public IEnumerable<Sensor> Test(Sensors jsonUpdate)
{
    foreach (var property in Properties)
    {
        var parameterExpression = Expression.Parameter(jsonUpdate.GetType());
        // You don't need call or GetMethod, you need to access Property
        var propertyCall = Expression.Property(parameterExpression, property);

        // Cast is redundant, and if you add it UpdateSensor will do nothing
        // UnaryExpression castToObject = Expression.Convert(propertyCall, typeof(JsonSensor<double>));
        var lambda = Expression.Lambda<Func<Sensors, JsonSensor<double>>>(propertyCall, parameterExpression);

        UpdateSensor(jsonUpdate, lambda);
    }

    // not relevant
    return null;
}