Binary Expression Class throws Invalid Operation Exception on Comparison Operators
I am modifying an open source program to create a generic filter for a datagrid in Silverlight. The code for the class is shown below.
public PropertyData Property { get; set; }
public FilterOperatorType FilterOperator { get; set; }
public string FilterValue { get; set; }
public Expression GetExpression<T>(ParameterExpression pe)
{
if (Property == null || Property.PropertyName == null)
return null;
PropertyInfo prop = typeof(T).GetProperty(Property.PropertyName);
Expression left = Expression.Property(pe, prop);
Expression right = null;
switch (prop.PropertyType.Name)
{
case "String":
right = Expression.Constant(FilterValue);
break;
case "Int32":
int val;
int.TryParse(FilterValue, out val);
right = Expression.Constant(val);
bre开发者_如何转开发ak;
case "Int64":
int.TryParse(FilterValue, out val);
Convert.ToInt32(val); //does not work
right = Expression.Constant(val);
break;
case "DateTime":
DateTime dt;
DateTime.TryParse(FilterValue, out dt);
right = Expression.Constant(dt);
break;
}
switch (FilterOperator)
{
case FilterOperatorType.Equal:
return Expression.Equal(left, right);
case FilterOperatorType.GreaterThan:
return Expression.GreaterThan(left, right);
case FilterOperatorType.GreaterThanOrEqual:
return Expression.GreaterThanOrEqual(left, right);
case FilterOperatorType.LessThan:
return Expression.LessThan(left, right);
case FilterOperatorType.LessThanOrEqual:
return Expression.LessThanOrEqual(left, right);
case FilterOperatorType.NotEqual:
return Expression.NotEqual(left, right);
}
return null;
}
}
Anytime I try to filter with an integer, I get an InvalidOperationException that state's: The binary operator Equal is not defined for the types 'System.Int64' and 'System.Int32'.
I understand why this exception is being thrown, however on the example program for this code I don't get any exceptions, due to the user's inputed integer being of type Int32, while in my application it is an Int64. Anyone have any ideas on how to fix this?
You need to parse the input as a long
rather than an int
.
精彩评论