简体   繁体   中英

CSharp -> Property getter expression does not work with Condition

I've got the following Code:

    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;
    }

This works if the Property is not null. For this check I changed the Code to:

    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;         
    }

Now I got the Exception: ArgumentException, the Expression of Type void could not be used for the return value of string!

It may not be the only thing that you need to do, but I think you want to use Expression.Condition rather than Expression.IfThenElse .

Currently you've got the equivalent of:

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

without any return. (As noted in the documentation, the overall type of the expression returned by IfThenElse is Void .)

You really want:

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

The latter is what Expression.Condition represents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM