C#可空数组 [英] C# Nullable arrays

查看:439
本文介绍了C#可空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有搜索功能,但我想 LocationID 是一个整数数组,而不仅仅是一个整数。我不知道如何做到这一点,因为我希望它也可为空。我看着做 INT?[] 但后来我不得不检查每一个条目的的HasValue 。有没有更好的办法?

这是我目前有:

 公众的ActionResult搜索(字符串?SearchString在,诠释?LocationId,
    约会时间?起始日期,日期时间?结束日期)


解决方案

数组总是引用类型,如字符串 - 所以他们的空。你只需要使用(只有的可以的使用)可空< T> ,其中T是一个非空值类型

所以,你可能想:

 公众的ActionResult搜索(字符串搜索字符串,INT [] locationIds,
                           约会时间?的startDate,日期时间?结束日期)

请注意,我已经改变了你的参数名称遵循.NET的命名规则,并改变 LocationId locationIds 以表明它是多个位置。

您可能还需要考虑改变参数类型为的IList< INT> 甚至的IEnumerable< INT> 更一般的,如:

 公众的ActionResult搜索(字符串搜索字符串,IList的< INT> locationIds,
                           约会时间?的startDate,日期时间?结束日期)

这方式主叫方可能会通过在列表与LT; INT方式> 例如:

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<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.

这篇关于C#可空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆