当尝试使用’foreach’迭代整数数组时,可以将元素的类型定义为’char’。

huangapple go评论67阅读模式
英文:

When trying to iterate over an integer array using 'foreach' it is possible to define the element's type as 'char'

问题

在C#中,我遇到了一件非常有趣的事情。例如,如果您尝试使用foreach语句迭代整数数组,您基本上可以将项目的类型定义为char。您可以参考下面的代码:

通常,您会这样写:

int[] arr = new int[] { 1, 2, 3, 4 };

foreach (int item in arr)
{
    Console.WriteLine(item);
}

但是,您也可以这样做:

int[] arr = new int[] { 1, 2, 3, 4 };

foreach (char item in arr)
{
    Console.WriteLine(item);
}

第一段代码将在控制台中写出所有数字。第二段代码将打印空白字符。我想知道为什么可以在foreach语句内部将int替换为char。然后,为什么会打印出空白字符?

英文:

I have encountered a very interesting thing in C#. For example, if you try to iterate over an array of integers using foreach statement, you basically can define item's type as char. For reference you can have a look at the code below:

Normally, you write this:

int[] arr = new int[] { 1, 2, 3, 4 };

foreach (int item in arr)
{
    Console.WriteLine(item);
}

But also, you can do this:

int[] arr = new int[] { 1, 2, 3, 4 };

foreach (char item in arr)
{
    Console.WriteLine(item);
}

The first code will write out all numbers in console. The second piece of code will print whitespaces. I want to know why it is possible to replace int with char inside foreach statement. And then, why whitespaces are getting printed?

答案1

得分: 2

当您在foreach循环中使用Console.WriteLine(item)并将char作为迭代变量时,它会尝试显示与每个int值对应的Unicode字符。由于这些字符是控制字符,在控制台输出中它们是不可见的,您会看到空白字符代替。

英文:

When you use Console.WriteLine(item) inside the foreach loop with char as the iteration variable, it attempts to display the Unicode character corresponding to each int value. Since these characters are control characters, they are not visible in the console output, and you see whitespace instead.

答案2

得分: 2

"char"的值为"1"与值为"'1'"的字符不同(其值为"49")

显示一个"int"时,会得到其数字表示(即数字)。而对于"char",它会被转换为其Unicode表示(一个字符)

更多信息请查看文档

这是ASCII表,为了简单起见(Unicode表有更多字符)

您可以看到字符"0"是"null","1"是"SOH",...字符"49"是"'1'","50"是"'2'"等等...

当尝试使用’foreach’迭代整数数组时,可以将元素的类型定义为’char’。

英文:

The char with value 1 is different than the char with value '1' (which has the value 49)

When displaying an int, you get the numerical representation (the number). When doing the same with a char, it's converted to its unicode representation (a character)

More informations in documentation

Here is the ascii table, for simplicity (the unicode one has way more characters)

You can see the character 0 is null, the 1 is SOH, ... the character 49 is '1', the 50 is '2' and so on...

当尝试使用’foreach’迭代整数数组时,可以将元素的类型定义为’char’。

huangapple
  • 本文由 发表于 2023年7月7日 03:39:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定