gpt4 book ai didi

C# 可空数组

转载 作者:可可西里 更新时间:2023-11-01 07:50:09 26 4
gpt4 key购买 nike

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

这是我目前拥有的:

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

最佳答案

数组始终是引用类型,string 也是如此。 - 所以它们已经可以为空。你只需要使用(并且只有可以使用)Nullable<T>其中 T 是不可为 null 的值类型。

所以你可能想要:

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

请注意,我已经更改了您的参数名称以遵循 .NET 命名约定,并更改了 LocationIdlocationIds以表明它适用于多个位置。

您可能还想考虑将参数类型更改为 IList<int>甚至 IEnumerable<int>更笼统,例如

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

这样调用者可以传入 List<int>例如。

关于C# 可空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16069997/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com