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

标签 c# arrays string char int

当我在 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.WriteLinea specific overload它需要一个 char[]。这最终被传递给 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[]

关于c# - 为什么 char 数组在控制台上显示内容,而 string 和 int 数组不在 c# 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57289863/

相关文章:

c# - 如何创建密码重置链接?

c# - F# List.map 在 C# 中等效?

c# - 在辅助监视器上最大化时设置 wpf 应用程序屏幕高度

PHP 在类数组中使用类变量

php - 如何将字符串截断为 PHP 中的前 20 个单词?

c# - TransactionSearch 的 PayPal Web 服务不遵守 StartDate/EndDate

javascript - 使用 jQuery 在 javascript 中迭代关联数组(键/值对),其中值是 jQuery 对象

javascript - 如果另一个数组具有相同的元素,则连接数组元素

php - 如何在 PHP 中查找字符串的所有子字符串

string - 将两个不同列上第 n 次出现的 'foo' 和 'bar' 替换为相应列中所提供文件的第 n 行的数字