c# - 创建动态表达式<Func<T,Y>>

标签 c# .net linq

我想创建一个动态 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/

相关文章:

c# - 需要帮助通过类访问 DropDownList

c# - 如何在 Visual Studio for Mac 中打开预先存在的 .NET Core 应用程序?

c# - 处理大型查询的超时

c# - 从 SharePoint 网站访问文件

c# - 卡在 while 循环中

.net - 如果模块已导入到 Powershell 中,如何删除该模块?

c# - 如何将 WPF 控件值绑定(bind)到方法?

c# - C# 中的 LINQ : Foreach inside linq

c# - 如何消除累加器中的条件?

c# - 动态 LINQ 强制转换为可为 null