开发者

What's the point using String.ToCharArray if a string is a char array itself?

开发者 https://www.devze.com 2022-12-23 05:32 出处:网络
string s = \"string\"; Console.WriteLine(s[1]); // returns t char[] chars = s.ToCharArray(); Console.WriteLine(chars[1]); // also returns t
string s = "string";
Console.WriteLine(s[1]); // returns t

char[] chars = s.ToCharArray();
Console.WriteLine(chars[1]); // also returns t

so what开发者_开发知识库 is the point in this method?


A string is not a char array. You are confusing the fact that it has an indexer returning char with it being a char array.


Just because you can write s[1] doesn't mean that a string is a char array, it meerely means string has an indexer that returns a char. The fact that indexers are accessed with the same syntax as array member access is a C# language feature.


System.String isn't a character array. If you need a character array (e.g. to pass as an argument to a method that's expecting one), you will need to do this conversion.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号