小编Jus*_*acy的帖子

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))
};
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)

c# nullable dynamic

33
推荐指数
1
解决办法
7140
查看次数

标签 统计

c# ×1

dynamic ×1

nullable ×1