我尝试在另一个问题中提出一个建议: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)
);
}
}
实施后,我得到以下例外情况,我并不理解。该异常指向以&#34; var createdEx =&#34;
开头的行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 :(得分:2)
在类型后添加问号的简写允许Nullable。您可能希望在这两个签名中更改它。请记住,这使您可以将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)
);
}
}
答案 1 :(得分:0)
通过添加问号,允许lambda返回可为空的日期时间:
var createdEx = Expression.Lambda<Func<TModel, DateTime?>>...