C#4:动态和可空的<>
所以我有一些代码在方法之间传递这个匿名对象:
var promo = new
{
Text = promo.Value,
StartDate = (startDate == null) ?
new Nullable<DateTime>() :
new Nullable<DateTime>(DateTime.Parse(startDate.Value)),
EndDate = (endDate == null) ?
new Nullable<DateTime>() :
new Nullable<DateTime>(DateTime.Parse(endDate.Value))
};
接收此匿名对象类型的方法将其类型声明为dynamic
:
private static bool IsPromoActive(dynamic promo)
{
return /* check StartDate, EndDate */
}
但是,在运行时,如果StartDate
或EndDate
设置为new Nullable<DateTime>(DateTime.Parse(...))
,则接收此dynamic
对象(名为promo
)的方法执行此操作:
if (promo.StartDate.HasValue && promo.StartDate > DateTime.Today ||
promo.EndDate.HasValue && promo.EndDate < DateTime.Today)
{
return;
}
它引发了一个异常:
Server Error in '/' Application.
'System.DateTime' does not contain a definition for 'HasValue'
这里发生了什么?关于Nullable
类型和dynamic
关键字,我不了解什么?
这个代码在我改变之前工作正常我移除了先前存储的struct
,StartDate
,StartDate
和EndDate
并用匿名类型替换它并将其作为dynamic
传递。
没有找到相关结果
已邀请:
1 个回复
铰齐插