[英]C# Nullable arrays
我有一个搜索功能,但我希望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
后删除了问号,因为它也是一个引用类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.