c#中空数组_C#可空数组

这篇博客讨论了如何在C#中将Search方法的LocationId参数从单个可空整数转换为可为空的整数数组。作者指出,由于数组本身已经是引用类型,因此默认就是可为空的。建议使用int[]而不是int?[],并建议考虑使用IList或IEnumerable来提供更大的灵活性,允许传入各种类型的集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

bd96500e110b49cbb3cd949968f18be7.png

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)

解决方案

Arrays are always reference types, as is string - so they're already nullable. You only need to use (and only can use) Nullable 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 or even IEnumerable to be more general, e.g.

public ActionResult Search(string searchString, IList locationIds,

DateTime? startDate, DateTime? endDate)

That way a caller could pass in a List for example.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值