代码之家  ›  专栏  ›  技术社区  ›  cd491415

可空数组,为什么需要它们

  •  0
  • cd491415  · 技术社区  · 7 年前

    private readonly decimal?[] _amounts = new decimal?[_count];
    
    4 回复  |  直到 7 年前
        1
  •  5
  •   Ousmane D.    7 年前

    宣布为 decimal?[] 表示数组包含的元素 可以是 null 或非空 .

    可空 ,数组可以存储的元素 不可能 .

    换句话说,, 读作“一个 可空 小数” ? 是指数组可以包含的元素,而不是数组本身,因为所有数组都是引用类型。

        2
  •  5
  •   BART    6 年前

    可空引用类型 : https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/nullable-reference-types

    但正如其他人提到的:

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

    表示数组中的值类型元素可以为null。 decimal decimal? 那你就可以了。

    在C#8.0和可空引用类型功能启用的情况下,如果要将引用类型分配为null,则应将其声明为可空引用类型,否则默认情况下会收到编译器警告。您可以这样声明一个:

    private decimal?[]? _amounts;
    

    现在它意味着数组中的两个元素都可以为null,并且整个数组(_amountsvariable)可以为null。

    ? 之前 [] -> SomeValueType?[] ? 后数组类型 SomeArrayType[] -&燃气轮机; SomeArrayType[]? 意味着您可以将null赋值给保存数组引用的变量。

        3
  •  1
  •   Yeldar Kurmangaliyev    7 年前

    此处的可空说明符不是指数组本身,而是指数组的内容。正如您正确地说的,数组本身是一种引用类型,因此,总是可nulable的(至少在C#8之前)。

    有几个不同的例子:

    decimal[] nonNullable = new decimal[2];
    nonNullable[0] = 1;             //OK, a non null item
    nonNullable[1] = null;          //Compile error: array doesn't accepts nulls
    nonNullable = null;             //OK, set the array reference to null
    
    decimal?[] nullable = new decimal?[2];
    nullable[0] = 1;                //OK, a non null item
    nullable[1] = null;             //OK, a null item (actually, a Nullable<decimal> instance)
    nullable = null;                //OK, set the array reference to null
    
        4
  •  1
  •   BlueMonkMN    7 年前

    数组对象本身和数组元素之间存在差异。当你使用 decimal?[] decimal 价值观如果你要用 decimal[]? null .

    为了解释差异,请考虑Alejandro发布的代码,以及该代码:

    decimal[]? reallyNullable = null;
    
    Array.Sort(reallyNullable); // ArgumentNullException -- there is no array here
    Array.Sort(nullable); // OK, assuming null can be compared to decimal.
    

    最后一行是OK的原因是这里实际引用了一个数组对象。唯一为空的是其中的一些值。