【问题标题】:Using System.DateTime in a C# Lambda expression gives an exception在 C# Lambda 表达式中使用 System.DateTime 会产生异常
【发布时间】:2011-11-19 01:44:09
【问题描述】:

我尝试实施另一个问题中提出的建议:Stackoverflow question

此处摘录:

 public static class StatusExtensions
    {
        public static IHtmlString StatusBox<TModel>(
            this HtmlHelper<TModel> helper,
            Expression<Func<TModel, RowInfo>> ex
        )
        {
            var createdEx =
                Expression.Lambda<Func<TModel, DateTime>>(
                    Expression.Property(ex.Body, "Created"),
                    ex.Parameters
                );
            var modifiedEx =
                Expression.Lambda<Func<TModel, DateTime>>(
                    Expression.Property(ex.Body, "Modified"),
                    ex.Parameters
                );
            var a = "a" + helper.HiddenFor(createdEx) +
                helper.HiddenFor(modifiedEx);
            return new HtmlString(
                "Some things here ..." +
                helper.HiddenFor(createdEx) +
                helper.HiddenFor(modifiedEx)
            );
        }
    }

实施后,我收到以下我不太了解的异常。异常指向以“var createdEx =”

开头的行
System.ArgumentException was unhandled by user code
  Message=Expression of type 'System.Nullable`1[System.DateTime]' cannot be used for return type 'System.DateTime'
  Source=System.Core
  StackTrace:

谁能帮助我并建议我可以做些什么来解决这个异常?

【问题讨论】:

    标签: c# datetime lambda expression-trees


    【解决方案1】:

    在类型后添加问号的简写允许 Nullable。您可能希望在此处更改两个签名中的内容。请记住,这使您可以将 null DateTimes 作为隐藏参数传递,这可能不是您想要的。相反,您可能希望保留此代码并确保只传递非空的 DateTime。

     public static class StatusExtensions
        {
            public static IHtmlString StatusBox<TModel>(
                this HtmlHelper<TModel> helper,
                Expression<Func<TModel, RowInfo>> ex
            )
            {
                var createdEx =
                    Expression.Lambda<Func<TModel, DateTime?>>(
                        Expression.Property(ex.Body, "Created"),
                        ex.Parameters
                    );
                var modifiedEx =
                    Expression.Lambda<Func<TModel, DateTime?>>(
                        Expression.Property(ex.Body, "Modified"),
                        ex.Parameters
                    );
                var a = "a" + helper.HiddenFor(createdEx) +
                    helper.HiddenFor(modifiedEx);
                return new HtmlString(
                    "Some things here ..." +
                    helper.HiddenFor(createdEx) +
                    helper.HiddenFor(modifiedEx)
                );
            }
        }
    

    【讨论】:

      【解决方案2】:

      通过添加问号允许 lambda 返回一个可为空的日期时间: var createdEx = Expression.Lambda&lt;Func&lt;TModel, DateTime?&gt;&gt;...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-16
        • 1970-01-01
        • 2016-05-30
        • 1970-01-01
        • 2014-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多