我有一个搜索功能,但我想LocationID成为一个整数数组,而不仅仅是一个整数。我不确定如何执行此操作,因为我希望它也可以为空。我已经看过了,int?[]但是我必须检查HasValue每个条目。有没有更好的办法?
这是我目前拥有的:
public ActionResult Search(string? SearchString, int? LocationId,
DateTime? StartDate, DateTime? EndDate)
数组始终是引用类型,string因此它们已经可以为空。您只需要使用(并且只能使用)Nullable<T>其中 T 是不可为空的值类型。
所以你可能想要:
public ActionResult Search(string searchString, int[] locationIds,
DateTime? startDate, DateTime? endDate)
请注意,我已更改您的参数名称以遵循 .NET 命名约定,并更改LocationId为locationIds表示它适用于多个位置。
您可能还想考虑将参数类型更改为IList<int>甚至IEnumerable<int>更通用,例如
public ActionResult Search(string searchString, IList<int> locationIds,
DateTime? startDate, DateTime? endDate)
这样,调用者就可以传入一个List<int>例子。
数组是引用类型,所以你不需要做任何事情,你已经可以通过null:
可以使用所有参数调用具有以下签名的方法null:
public ActionResult Search(string SearchString, int[] LocationIds,
DateTime? StartDate, DateTime? EndDate)
foo.Search(null, null, null, null);
请注意:我还删除了之后的问号,string因为它也是一个引用类型。