我想创建一个动态 Expression<Func<T,Y>>
.这是适用于字符串但不适用于 DateTime 的代码。通过不起作用我的意思是,我得到这个异常(exception):
"Expression of type 'System.Nullable`1[System.DateTime]' cannot be used for return type '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);
我需要更改 object
吗?到其他类型?如果是,那么是哪个?如您所见,我正在尝试动态获取 PropertyInfo 并将其用作 Func 中的第二个参数。
最佳答案
对于值类型,您需要明确地执行装箱(即转换为 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);
关于c# - 创建动态表达式<Func<T,Y>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9860620/