2011-11-19 30 views
2

我試圖執行,在另一個問題想出了一個建議:Stackoverflow question在C#Lambda表達式使用的System.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) 
      ); 
     } 
    } 

實現時我正在以下例外,我不明白。異常點開始與線「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: 

誰能幫助我,並建議我可以做些什麼來解決異常?

回答

0

允許拉姆達通過添加問號返回可爲空的日期時間: var createdEx = Expression.Lambda<Func<TModel, DateTime?>>...

2

類型之後加入一個問號的速記允許可爲空。您可能會想要在這兩個簽名中更改它。請記住,這可以讓您將null DateTimes作爲隱藏參數傳遞,但這可能不是您想要的。您可能希望保留此代碼,並確保您只將它傳遞給非null 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) 
      ); 
     } 
    }