为什么 char 数组在控制台上显示内容,而 string 和 int 数组不在 c# 中?

Why does char array display contents on console while string and int arrays dont in c#?

当 i 运行 Console.WriteLine() 在 int 或字符串数​​组上时,它会打印 (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.WriteLinea specific overload which takes a char[]. This ends up being passed to TextWriter.Write(char[]),将其写为字符串。

参见 referencesource

如果您深入挖掘,文档会提示这一点。

Console.WriteLine(char[]):

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 this TextWriter from the buffer character array starting at position index.

This overload is equivalent to the Write(Char[]) overload for each character in buffer between index and (index + count).

你可以看到 char[] 本身没有什么特别之处,写成:

Console.WriteLine((object)char_array);  

这会调用 Console.WriteLine(object) 重载,打印 System.Char[].