可空数组以及为什么需要它们 [英] Nullable Array and Why Do We Need Them

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

问题描述

我看到了这样的代码,并且我将其理解为使数组可为空,但是我不明白为什么我们需要它,因为数组是ref类型,因此它们已经可以为空.

I see code like this and I understand it as making an array nullable but I dont understand why do we need it since arrays are ref types, so they are already nullable.

所以,我的问题是为什么我们需要这个?

So, my question is why do we need this?

private readonly decimal?[] _amounts = new decimal?[_count];

推荐答案

值得一提的是,在C#8.0中,您可以使用可空引用类型: https://docs.microsoft.com/zh-我们/dotnet/csharp/tutorials/nullable-reference-types

It's worth to mention that from C# 8.0 you can have a nullable reference type: https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/nullable-reference-types

但正如其他人提到的那样:

but as others mentioned this:

private readonly decimal?[] _amounts = new decimal?[_count];

表示数组中的value-type元素可以为null. decimal 是值类型,通常不能将null赋予它,但是如果您具有 decimal?,那么可以.

means the value-type elements in array can be null. decimal is value type and normally you can't assing null to it but if you have decimal? then you can.

启用C#8.0和可为空的引用类型功能后,如果要为它们赋予null,则应将引用类型声明为可为空的引用类型,否则默认情况下会收到编译器警告.您可以这样声明:

With C# 8.0 and nullable reference types feature enabled you should declare reference types as nullable reference types if you want to assing null to them, otherwise you'll get compiler warning by default. You can declare one like this:

private decimal?[]? _amounts;

现在,这意味着数组中的两个元素都可以为null,整个数组(_amounts变量)可以为null.

Now it means that both elements in array can be null and entire array (_amounts variable) may be null.

因此,通常在元素值类型?之后和 [] -> SomeValueType?[] <前的问号/code>表示数组中的元素可以为null.从C#8.0(在项目中启用了功能)开始,在数组类型为 SomeArrayType [] -> SomeArrayType []后问号??意味着您可以将null分配给保存对数组的引用的变量.

So in general the question mark after element value type ? and before [] -> SomeValueType?[] means that elements in array can be null. From C# 8.0 (with feature enabled in project) question mark ? after array type SomeArrayType[] -> SomeArrayType[]? means that you can assign null to variable that holds reference to the array.

这篇关于可空数组以及为什么需要它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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