3

例如,当我写道:

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

它说无法将 null 转换为 'char',因为它是不可为空的值类型

如果我需要清空该字符数组,有解决方案吗?

4

6 回答 6

10

使用可为空的字符:

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';
于 2012-10-10T19:54:55.840 回答
3

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

你可以这样做:

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

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

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

于 2012-10-10T19:54:37.313 回答
2

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

test[2] = default(char);

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

于 2012-10-10T19:54:18.577 回答
2

你可以这样做:

test[2] = Char.MinValue;

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

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

还,Char.MinValue == default(char)

于 2012-10-10T19:55:58.470 回答
1

您可以将 test 设置为 null

test = null;

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

于 2012-10-10T19:54:18.993 回答
0

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

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

这会改变 的长度 ( Count) List<>

于 2012-10-10T20:12:53.013 回答