简体   繁体   English

C#Nullable数组

[英]C# Nullable arrays

I have a search function, but I would like LocationID to be an array of integers rather than just a single integer. 我有一个搜索功能,但我希望LocationID是一个整数数组而不是一个整数。 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. 我看过做int?[]但是我必须检查每个条目的HasValue Is there a better way? 有没有更好的办法?

This is what I currently have: 这就是我目前拥有的:

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

Arrays are always reference types, as is string - so they're already nullable. 数组总是引用类型,就像string - 所以它们已经可以为空了。 You only need to use (and only can use) Nullable<T> where T is a non-nullable value type. 你只需要使用(并且只能使用) 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 LocationId to locationIds to 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, eg 您可能还需要考虑将参数类型更改为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>

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 string as it is a reference type as well. 请注意:我还在string后删除了问号,因为它也是一个引用类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM