C#Nullable数组

我有一个搜索function,但我希望LocationID是一个整数数组而不是一个整数。 我不知道该怎么做,因为我希望它也可以为空。 我看过做int?[]但是我必须检查每个条目的HasValue 。 有没有更好的办法?

这就是我目前所拥有的:

 public ActionResult Search(string? SearchString, int? LocationId, DateTime? StartDate, DateTime? EndDate) 

数组总是引用类型,就像string – 所以它们已经可以为空了。 您只需要使用(并且只能使用) Nullable ,其中T是不可为空的值类型。

所以你可能想要:

 public ActionResult Search(string searchString, int[] locationIds, DateTime? startDate, DateTime? endDate) 

请注意,我已将参数名称更改为遵循.NET命名约定,并将LocationId更改为locationIds以指示它适用于多个位置。

您可能还需要考虑将参数类型更改为IList或甚至更改为IEnumerable ,例如

 public ActionResult Search(string searchString, IList locationIds, DateTime? startDate, DateTime? endDate) 

这样,调用者可以传入List

数组是引用类型,因此您不必执行任何操作,您已经可以传递null

可以使用以下所有参数调用具有以下签名的方法:

 public ActionResult Search(string SearchString, int[] LocationIds, DateTime? StartDate, DateTime? EndDate) foo.Search(null, null, null, null); 

请注意:我还在string后删除了问号,因为它也是一个引用类型。