当我在 int 或字符串数组上运行 Console.WriteLine() 时,它会打印 (System.String[]), (System.Int32[])。 但是我在使用 char 数组执行此操作时,它显示的内容就好像它们是一个字符串一样。这种奇怪的行为是怎么回事? (ihgfedcba) 是它显示的内容。谁能解释为什么会这样?
public static void Test(){
string[] words_array = new string[9];
words_array[0] = "football";
words_array[1] = "handball";
words_array[2] = "Harry Potter";
words_array[3] = "Prometheus";
words_array[4] = "strengh";
words_array[5] = "Muscles";
words_array[6] = "weakness";
words_array[7] = "beauty";
words_array[8] = "Ali";
System.Console.WriteLine(words_array);
int[] int_array = new int[9];
int_array[0] = 0;
int_array[1] = 1;
int_array[2] = 2;
int_array[3] = 3;
int_array[4] = 4;
int_array[5] = 5;
int_array[6] = 6;
int_array[7] = 7;
int_array[8] = 8;
System.Console.WriteLine(int_array);
char[] char_array = new char[9];
char_array[0] = 'i';
char_array[1] = 'h';
char_array[2] = 'g';
char_array[3] = 'f';
char_array[4] = 'e';
char_array[5] = 'd';
char_array[6] = 'c';
char_array[7] = 'b';
char_array[8] = 'a';
System.Console.WriteLine(char_array);
}
最佳答案
Console.WriteLine
有 a specific overload它需要一个 char[]
。这最终被传递给 TextWriter.Write(char[])
,将其写为字符串。
参见 referencesource .
如果您深入挖掘,文档会提示这一点。
Writes the specified array of Unicode characters, followed by the current line terminator, to the standard output stream.
TextWriter.Write(char[], int, int)
:
This method will write
count
characters of data into thisTextWriter
from the buffer character array starting at positionindex
.This overload is equivalent to the
Write(Char[])
overload for each character inbuffer
betweenindex
and (index + count
).
你可以看到 char[]
本身并没有什么特别之处:
Console.WriteLine((object)char_array);
这会调用 Console.WriteLine(object)
重载,打印 System.Char[]
。
关于c# - 为什么 char 数组在控制台上显示内容,而 string 和 int 数组不在 c# 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57289863/