CSharp - >属性getter表达式不适用于Condition

时间:2014-02-05 10:43:03

标签: c# lambda expression

我有以下代码:

    public static Func<object, string> GetPropGetter(Type objectType, string propertyName)
    {
        ParameterExpression paramExpression = Expression.Parameter(typeof(object), "value");

        Expression e = Expression.Convert(paramExpression, objectType);

        foreach (var name in propertyName.Split('.'))
        {
            e = Expression.Property(e, name);
        }

        Expression propertyGetterExpression = Expression.Call(e, typeof(object).GetMethod("ToString", Type.EmptyTypes));

        Func<object, string> result =
            Expression.Lambda<Func<object, string>>(propertyGetterExpression, paramExpression).Compile();

        return result;
    }

如果Property不为null,则此方法有效。对于此检查,我将代码更改为:

    public static Func<object, string> GetPropGetter(Type objectType, string propertyName)
    {
        ParameterExpression paramExpression = Expression.Parameter(typeof(object), "value");

        Expression e = Expression.Convert(paramExpression, objectType);

        foreach (var name in propertyName.Split('.'))
        {
            e = Expression.Property(e, name);
        }

        Expression propertyGetterExpression = Expression.IfThenElse(Expression.Equal(Expression.Default((e as MemberExpression).Type), e), Expression.Constant(""), Expression.Call(e, typeof(object).GetMethod("ToString", Type.EmptyTypes)));


        Func<object, string> result =
            Expression.Lambda<Func<object, string>>(propertyGetterExpression, paramExpression).Compile();

        return result;         
    }

现在我得到了Exception:ArgumentException,类型void的Expression不能用于string的返回值!

1 个答案:

答案 0 :(得分:4)

它可能不是您需要做的唯一事情,但我认为您希望使用Expression.Condition而不是Expression.IfThenElse

目前你已经相当于:

if (condition) {
    default(...);
} else {
    property-getters
}

没有任何回报。 (如文档中所述,IfThenElse返回的表达式的总体类型为Void。)

你真的想要:

return condition ? default(...) : property-getters;

后者是Expression.Condition所代表的。