是否可能从List返回null ?

本文关键字:返回 null DateTime List 是否 | 更新日期: 2023-09-27 18:12:17

我有一个接口和类

界面

List<DateTime> GetDates();

实现上述接口的类

public  List<DateTime> GetDates()
{
    IEnumerable<DateTime> MyDates = GetAllMyDates();
    IEnumerable<DateTime> ModifiedDates = null
    if (MyDates != null && MyDates.Count() > 0)
    {
        AllDates = MyDates.Where(....Some filter)
    }
    return AllDates.ToList();
}

添加了?返回错误

类型'List'必须是一个非空值类型,以便将其用作泛型类型或方法'Nullable'中的参数'T'

搜索错误,但无法找出我做错了什么,或者如果它不可能做到这一点?

是否可能从List<DateTime>返回null ?

由于List<T>是引用类型,您可以只返回null:

public List<DateTime> GetDates()
{
    IEnumerable<DateTime> MyDates = GetAllMyDates();
    IEnumerable<DateTime> ModifiedDates = null;
    if (MyDates != null && MyDates.Count() > 0)
    {
        AllDates = MyDates.Where(....Some filter)
        return AllDates.ToList();
    }
    return null;
}