среда, 19 сентября 2012 г.

Expression.Property breaking change in .NET 4.0


Если вы переезжаете на .NET 4.0 и используете expression trees то возможно вас заинтересует, что раньше такой код был валиден и для статических свойств:

var comparerExpr = Expression.Property(Expression.Constant(comparerType), comparerProperty);

Теперь же требуется дополнительная проверка:

var comparerExpr = Expression.Property(isStatic ? null : Expression.Constant(comparerType), comparerProperty);

Все дело во внутренностях метода Expression.Property!

Было:

public static MemberExpression Property(Expression expression, PropertyInfo property)
{
    if (property == null)
    {
        throw Error.ArgumentNull("property");
    }
    if (!property.CanRead)
    {
        throw Error.PropertyDoesNotHaveGetter(property);
    }
    if (!property.GetGetMethod(true).IsStatic)
    {
        if (expression == null)
        {
            throw Error.ArgumentNull("expression");
        }
        if (!AreReferenceAssignable(property.DeclaringType, expression.Type))
        {
            throw Error.PropertyNotDefinedForType(property, expression.Type);
        }
    }
    return new MemberExpression(expression, property, property.PropertyType);
}

Стало:

public static MemberExpression Property(Expression expression, PropertyInfo property)
{
    ContractUtils.RequiresNotNull(property, "property");
    MethodInfo info = property.GetGetMethod(true) ?? property.GetSetMethod(true);
    if (info == null)
    {
        throw Error.PropertyDoesNotHaveAccessor(property);
    }
    if (info.IsStatic)
    {
        if (expression != null)
        {
            throw new ArgumentException(Strings.OnlyStaticPropertiesHaveNullInstance, "expression");
        }
    }
}


Wider Two Column Modification courtesy of The Blogger Guide