C# 如何将char数组的值设置为null?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12827251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:34:27  来源:igfitidea点击:

how to set a value of char array to null?

c#arraysnullchar

提问by Hendra Anggrian

for example when I wrote:

例如,当我写道:

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

it says Cannot convert null to 'char' because it is a non-nullable value type

它说不能将 null 转换为 'char' 因为它是一个不可为空的值类型

if I need to empty that array of char, is there a solution?

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

采纳答案by D Stanley

Use a nullable char:

使用可空字符:

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

The drawback is you have to check for a value each time you accessthe array:

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

char c = test[1];  // illegal

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

or you could use a "magic" char value to represent null, like \0:

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

char[] test = new char[3] {a,b,c};
test[2] = '
test[2] = default(char);
';

回答by jheddings

As the error states, charis non-nullable. Try using defaultinstead:

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

test = null;

Note that this is essentially a null byte '\0'. This does not give you a nullvalue for the index. If you truly need to consider a nullscenario, the other answers here would work best (using a nullable type).

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

回答by Nikola Davidovic

you can set test to null

您可以将测试设置为空

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

but not test[2] because it is char - hence value type

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

回答by Matt Burland

You can't do it because, as the error says, char is a value type.

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

You could do this:

你可以这样做:

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

because you are now using the nullable char.

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

If you don't want to use a nullable type, you will have to decide on some value to represent an empty cell in your array.

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

回答by Gromer

You could do:

你可以这样做:

test[2] = Char.MinValue;

test[2] = Char.MinValue;

If you had tests to see if a value was "null" somewhere in your code, you'd do it like this:

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

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

Also, Char.MinValue == default(char)

还, Char.MinValue == default(char)

回答by Jeppe Stig Nielsen

I don't know the reason for your question, but if instead you use List<>, you could say

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

##代码##

This changes the length (Count) of the List<>.

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