如何在访问 DateTime 时不出错? .NET 中的属性是否继续?

How to not get errors accessing DateTime? properties in .NET with continue?

我有一个循环遍历可为 null 的 DateTimes,continues 如果它们为空则循环,否则使用它们的 Year 和 Month 属性。

这是一个简化的例子:

public static void Main()
{
    var dateTimes = GetDateTimes();
    
    foreach (var dateTime in dateTimes)
    {
        if (dateTime is null)
            continue;
        
        Console.WriteLine(dateTime.Year.ToString(), dateTime.Month.ToString());
    }
}

public static IEnumerable<DateTime?> GetDateTimes()
{
    return new List<DateTime?> { new DateTime(2021, 03, 22), null, DateTime.Now };
}

但是,C# 似乎无法判断,在 if-continue 之后,dateTime 项不为空,并且不允许我访问它的属性。

即使 if (dateTime != null) 它仍然抱怨?

有没有办法让 C# 确认正确的类型,最好使用 if-continue 结构?

该项目使用.NET Core 3.1。

demo

使用 dateTime.GetValueOrDefaultdateTime.Value 解决了问题。