c#可空数组
本文关键字:数组 | 更新日期: 2023-09-27 18:09:48
我有一个搜索函数,但我希望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
之后额外删除了问号,因为它也是引用类型。