Expression.Property的Expression.Convert类型 [英] Expression.Convert type for Expression.Property
本文介绍了Expression.Property的Expression.Convert类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试转换参数表达式,但在转换为值类型时遇到了麻烦.以下是我的代码示例:
I'm trying to convert a Parameter expression and having trouble with converting to value types. Below is a sample of my code:
public static MemberExpression ConvertToType(ParameterExpression sourceParameter,
PropertyInfo propertyInfo,
TypeCode typeCode)
{
var sourceExpressionProperty = Expression.Property(sourceParameter, sourceProperty);
//throws an exception if typeCode is a value type.
Expression convertedSource = Expression.Convert(sourceExpressionProperty,
Type.GetType("System." + typeCode));
return convertedSource;
}
我收到以下无效的操作异常:
I get the following invalid operation exception:
No coercion operator is defined between types 'System.String' and 'System.Decimal'.
对于此转换的任何帮助,将不胜感激.
Any help with this conversion would be greatly appreciated.
推荐答案
我使用的解决方案是:
private static Expression GetConvertedSource(ParameterExpression sourceParameter,
PropertyInfo sourceProperty,
TypeCode typeCode)
{
var sourceExpressionProperty = Expression.Property(sourceParameter,
sourceProperty);
var changeTypeCall = Expression.Call(typeof(Convert).GetMethod("ChangeType",
new[] { typeof(object),
typeof(TypeCode) }),
sourceExpressionProperty,
Expression.Constant(typeCode)
);
Expression convert = Expression.Convert(changeTypeCall,
Type.GetType("System." + typeCode));
var convertExpr = Expression.Condition(Expression.Equal(sourceExpressionProperty,
Expression.Constant(null, sourceProperty.PropertyType)),
Expression.Default(Type.GetType("System." + typeCode)),
convert);
return convertExpr;
}
请注意Expression.Condition
可以处理空值.
这篇关于Expression.Property的Expression.Convert类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文