【问题标题】:how to set a value of char array to null?如何将char数组的值设置为null?
【发布时间】:2012-10-01 09:23:08
【问题描述】:

例如当我写的时候:

Char[] test = new Char[3] {a,b,c};
test[2] = null;

上面写着 Cannot convert null to 'char' because it is an non-nullable value type

如果我需要清空该 char 数组,是否有解决方案?

【问题讨论】:

标签: c# arrays null char


【解决方案1】:

如错误所述,char 不可为空。尝试改用default

test[2] = default(char);

请注意,这本质上是一个空字节“\0”。这不会为您提供索引的null 值。如果您确实需要考虑 null 场景,这里的其他答案将最有效(使用可为空的类型)。

【讨论】:

  • default(char) 给出the null character。为什么不明确地说test[2] = '\0';?我建议(如果您想将此字符用作一种“魔法值”)。
  • 仅出于一致性考虑...我在很多情况下使用default,因为这些类型事先并不知道(即泛型或反射)。它帮助我保持default =>“未指定”或“未初始化”的一致心智模型。
【解决方案2】:

您可以将 test 设置为 null

test = null;

但不是 test[2],因为它是 char - 因此是值类型

【讨论】:

    【解决方案3】:

    你不能这样做,因为正如错误所说,char 是一种值类型。

    你可以这样做:

    char?[] test = new char?[3]{a,b,c};
    test[2] = null;
    

    因为您现在使用可空字符。

    如果您不想使用可为空的类型,则必须确定某个值来表示数组中的空单元格。

    【讨论】:

      【解决方案4】:

      使用可为空的字符:

      char?[] test = new char?[3] {a,b,c};
      test[2] = null;
      

      缺点是每次访问数组时都必须检查一个值:

      char c = test[1];  // illegal
      
      if(test[1].HasValue)
      {
          char c = test[1].Value;
      }
      

      或者您可以使用“魔术”字符值来表示null,例如\0

      char[] test = new char[3] {a,b,c};
      test[2] = '\0';
      

      【讨论】:

      • 一个快速的建议可能是使用default(char) 作为“魔法”值。恕我直言,它提供了一个类似的心理模型来考虑“未初始化”或“未指定”的值。
      • 很公平 - 使用 \0 作为 null 是我 C++ 时代的遗留物 :)
      • 这没什么错...毕竟在这种情况下它们是相同的。
      • '\0' 完美运行。很抱歉,我不得不忽略上面的前两包代码,因为我正在寻找最简单的代码。谢谢老哥!
      【解决方案5】:

      你可以这样做:

      test[2] = Char.MinValue;

      如果您有测试来查看代码中某处的值是否为“null”,您可以这样做:

      if (test[someArrayIndex] == Char.MinValue)
      {
         // Do stuff.
      }
      

      另外,Char.MinValue == default(char)

      【讨论】:

        【解决方案6】:

        我不知道你提问的原因,但如果你改用List<>,你可以说

        List<char> test = new List<char> { a, b, c, };
        test.RemoveAt(2);
        

        这会更改 List&lt;&gt; 的长度 (Count)。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-08-08
          • 2017-09-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-13
          相关资源
          最近更新 更多