我想创造一个动态Expression<Func<T,Y>>
.这是适用于字符串但不适用于DateTime的代码.通过不起作用我的意思是,我得到这个例外:
"类型'System.Nullable`1 [System.DateTime]'的表达式不能用于返回类型'System.Object'"
任何人都可以analyze
犯错吗?
Type type = typeof(DSVPNProjection);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = arg;
PropertyInfo propertyInfo = type.GetProperty(sidx);
expr = Expression.Property(expr, propertyInfo);
var expression =
Expression.Lambda<Func<DSVPNProjection, object>>(expr, arg);
Run Code Online (Sandbox Code Playgroud)
我是否需要将其更改object
为其他类型?如果是,那么哪个?正如您所看到的,我正在尝试动态获取PropertyInfo并将其用作Func中的第二个参数.
Tho*_*que 14
对于值类型,您需要显式执行装箱(即转换为Object
):
Type type = typeof(DSVPNProjection);
ParameterExpression arg = Expression.Parameter(type, "x");
Expression expr = null;
PropertyInfo propertyInfo = type.GetProperty(sidx);
expr = Expression.Property(arg, propertyInfo);
if (propertyInfo.PropertyType.IsValueType)
expr = Expression.Convert(expr, typeof(object));
var expression =
Expression.Lambda<Func<DSVPNProjection, object>>(expr, arg);
Run Code Online (Sandbox Code Playgroud)