C# Nullable arrays

偶尔善良 提交于 2019-12-23 06:57:01

问题


I have a search function, but I would like LocationID to be an array of integers rather than just a single integer. I'm not sure how to do this since I want it to also be nullable. I've looked at doing int?[] but then I'd have to check the HasValue of every single entry. Is there a better way?

This is what I currently have:

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

回答1:


Arrays are always reference types, as is string - so they're already nullable. You only need to use (and only can use) Nullable<T> where T is a non-nullable value type.

So you probably want:

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

Note that I've changed your parameter names to follow .NET naming conventions, and changed LocationId to locationIds to indicate that it's for multiple locations.

You might also want to consider changing the parameter type to IList<int> or even IEnumerable<int> to be more general, e.g.

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

That way a caller could pass in a List<int> for example.




回答2:


Arrays are reference types, so you don't have to do anything, you already can pass null:

A method with the following signature can be called with all parameters as null:

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


foo.Search(null, null, null, null);

Please note: I additionally removed the question mark after string as it is a reference type as well.



来源:https://stackoverflow.com/questions/16069997/c-sharp-nullable-arrays

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!