为什么我不能在C#中的char数组上使用.ToString()方法? [英] Why can't I use a .ToString() method on a char array in C#?

查看:149
本文介绍了为什么我不能在C#中的char数组上使用.ToString()方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个练习,要求我向用户询问一个字符串,然后反转该字符串并将其打印到控制台.我是这样写的:

I am working through an exercise where I am supposed to ask the user for a string, then reverse the string and print it out to the console. I wrote this:

        Console.WriteLine("Please enter a string of characters: ");
        char[] words = Console.ReadLine().ToCharArray();
        Console.WriteLine("You entered {0}, the reverse of which is {1}", words.ToString(), words.Reverse().ToString());

哪个没有用.显然,将一个char数组发送到.ToString()会返回"System.Char []",反之则返回"System.Linq.Enumerable + d__a0`1 [System.Char]".

Which did not work. Apparently sending a char array to .ToString() gives back "System.Char[]" and reversing it gives back "System.Linq.Enumerable+d__a0`1[System.Char]".

我了解到.ToString()无法处理char数组,而不得不使用新的字符串构造函数,因此我将代码重写为此,现在可以工作了:

I learned that .ToString() cannot handle a char array and instead I had to use the new string constructor, so I rewrote my code to this and it works now:

        Console.WriteLine("Please enter a string of characters: ");
        char[] words = Console.ReadLine().ToCharArray();
        Console.WriteLine("You entered {0}, the reverse of which is {1}", new string(words), new string(words.Reverse().ToArray()));

我的问题是为什么我不能在char数组上使用.ToString()? ToString的摘要含糊地指出返回一个代表当前对象的字符串",这对我来说意味着我将得到一个代表我正在发送的char数组的字符串.我想念什么?

My question is why can't I use .ToString() on a char array? The summary of ToString vaguely states "Returns a string that represents the current object," which meant to me I would get a string back that represents the char array I am sending it. What am I missing?

推荐答案

尽管我还没有找到具体的证据(到目前为止).我相信您不能在char数组上使用它,因为数组类型是引用类型表示它们包含对实际值的引用,而不是每个字符的值.如我的评论所述,它返回"System.Char []";它返回 ToString的默认值

While I can't find concrete proof of this (as of yet). I believe you cannot use it on a char array as Array types are reference types meaning they hold references to the actual values rather than the value of each character. It returns "System.Char[]" as stated in my comment; it returns the default value for ToString

编辑

这是我一直在寻找的证据 https://stackoverflow.com/a/1533770/1324033

This was the proof I was looking for https://stackoverflow.com/a/1533770/1324033

这篇关于为什么我不能在C#中的char数组上使用.ToString()方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆