所以我有一些代码在方法之间传递这个匿名对象:
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))
};
Run Code Online (Sandbox Code Playgroud)
接收此匿名对象类型的方法将其类型声明为dynamic:
private static bool IsPromoActive(dynamic promo)
{
return /* check StartDate, EndDate */
}
Run Code Online (Sandbox Code Playgroud)
在运行时,然而,如果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;
}
Run Code Online (Sandbox Code Playgroud)
它引发了一个异常:
Server Error in '/' …Run Code Online (Sandbox Code Playgroud)