例如,当我写道:
Char[] test = new Char[3] {a,b,c};
test[2] = null;
它说无法将 null 转换为 'char',因为它是不可为空的值类型
如果我需要清空该字符数组,有解决方案吗?
使用可为空的字符:
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';
你不能这样做,因为正如错误所说, char 是一种值类型。
你可以这样做:
char?[] test = new char?[3]{a,b,c};
test[2] = null;
因为您现在正在使用可为空的字符。
如果您不想使用可为空的类型,则必须确定某个值来表示数组中的空单元格。
如错误所述,char
不可为空。尝试default
改用:
test[2] = default(char);
请注意,这本质上是一个空字节“ \0
”。这不会为您提供null
索引值。如果您确实需要考虑一个null
场景,那么这里的其他答案效果最好(使用可为空的类型)。
你可以这样做:
test[2] = Char.MinValue;
如果您有测试来查看代码中某处的值是否为“null”,您可以这样做:
if (test[someArrayIndex] == Char.MinValue)
{
// Do stuff.
}
还,Char.MinValue == default(char)
您可以将 test 设置为 null
test = null;
但不是 test[2] 因为它是 char - 因此是值类型
我不知道你的问题的原因,但如果你改用List<>
,你可以说
List<char> test = new List<char> { a, b, c, };
test.RemoveAt(2);
这会改变 的长度 ( Count
) List<>
。