C#Nullable数组

Pr0*_*r0n 15 c# arrays nullable

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

这就是我目前拥有的:

public ActionResult Search(string? SearchString, int? LocationId,
    DateTime? StartDate,  DateTime? EndDate)
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 29

数组总是引用类型string- 所以它们已经可以为空了.你只需要使用(且仅使用),Nullable<T>其中T是一个非空的值类型.

所以你可能想要:

public ActionResult Search(string searchString, int[] locationIds,
                           DateTime? startDate,  DateTime? endDate)
Run Code Online (Sandbox Code Playgroud)

请注意,我已经改变了你的参数名称遵循.NET的命名规则,并改变LocationIdlocationIds以表明它是多个位置.

您可能还需要考虑将参数类型更改为IList<int>甚至IEnumerable<int>更一般,例如

public ActionResult Search(string searchString, IList<int> locationIds,
                           DateTime? startDate,  DateTime? endDate)
Run Code Online (Sandbox Code Playgroud)

这样一来,呼叫者可以传递一个List<int>例子.


Dan*_*rth 10

数组是引用类型,因此您无需执行任何操作,您已经可以通过null:

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

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


foo.Search(null, null, null, null);
Run Code Online (Sandbox Code Playgroud)

请注意:我之后还删除了问号,string因为它也是一个参考类型.