问题
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());
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]".
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()));
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?
回答1:
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
EDIT
This was the proof I was looking for https://stackoverflow.com/a/1533770/1324033
回答2:
You recieve that value becouse that is default value of char[] array and generally object. When you want change .ToString() behaviour for your case, you can override default ToString() method by using (for example) extension method.
来源:https://stackoverflow.com/questions/16720544/why-cant-i-use-a-tostring-method-on-a-char-array-in-c