C# 可空数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16069997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Nullable arrays
提问by Pr0n
I have a search function, but I would like LocationIDto 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 HasValueof every single entry. Is there a better way?
我有一个搜索功能,但我想LocationID成为一个整数数组,而不仅仅是一个整数。我不知道该怎么做,因为我希望它也可以为空。我已经看过了,int?[]但后来我必须检查HasValue每个条目的 。有没有更好的办法?
This is what I currently have:
这是我目前拥有的:
public ActionResult Search(string? SearchString, int? LocationId,
DateTime? StartDate, DateTime? EndDate)
采纳答案by Jon Skeet
Arrays are always reference types, as is string- so they're alreadynullable. You only need to use (and only canuse) Nullable<T>where T is a non-nullable value type.
数组始终是引用类型,原样string- 所以它们已经可以为空。你只需要使用(且仅可使用),Nullable<T>其中T是一个非空的值类型。
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 LocationIdto locationIdsto indicate that it's for multiple locations.
请注意,我已将您的参数名称更改为遵循 .NET 命名约定,并更改LocationId为locationIds以指示它用于多个位置。
You might also want to consider changing the parameter type to IList<int>or even IEnumerable<int>to be more general, e.g.
您可能还需要考虑将参数类型更改为IList<int>甚至IEnumerable<int>更通用,例如
public ActionResult Search(string searchString, IList<int> locationIds,
DateTime? startDate, DateTime? endDate)
That way a caller could pass in a List<int>for example.
这样调用者就可以传入一个List<int>例子。
回答by Daniel Hilgarth
Arrays are reference types, so you don't have to do anything, you already can pass null:
数组是引用类型,所以你不需要做任何事情,你已经可以通过null:
A method with the following signature can be called with all parameters as null:
可以使用所有参数调用具有以下签名的方法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 stringas it is a reference type as well.
请注意:我还删除了后面的问号,string因为它也是引用类型。

