string.ToCharArray() 是否需要枚举?
到底为什么有人会在枚举字符串中的字符之前将其转换为 char[] 呢?网络上随处可见的初始化 System.Security.SecureString 的常规模式如下:
SecureString secureString = new SecureString();
foreach (char c in "fizzbuzz".ToCharArray())
{
secureString.AppendChar(c);
}
调用 ToCharArray() 对我来说没有任何意义。有人能告诉我这里是否错了吗?
Why on Earth would someone convert a string to a char[] before enumerating the characters in it? The regular pattern for initializing a System.Security.SecureString found all around the net follows:
SecureString secureString = new SecureString();
foreach (char c in "fizzbuzz".ToCharArray())
{
secureString.AppendChar(c);
}
Calling ToCharArray() makes no sense for me. Could someone tell whether I am wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
string
实现了IEnumerable
,因此在此上下文中没有必要。您唯一需要ToCharArray
的时候是您实际上需要一个数组的时候。我的猜测是,大多数调用
ToCharArray
的人不知道string
实现了IEnumerable
(尽管据我所知它总是如此) 。Since
string
implementsIEnumerable<char>
, it's not necessary in this context. The only time you needToCharArray
is when you actually need an array.My guess is that most people who call
ToCharArray
don't know thatstring
implementsIEnumerable
(even though as far as I know it always has).实际上这很糟糕,因为它
很多不必要的工作...
那是因为字符串是不可变的,并且不允许给出指向其内部数组的指针,所以ToCharArray() 进行复制而不是强制转换。
也就是说:
您可以将字符串枚举为 char[] 但是:
您不能:
如果您要枚举并希望在某个时刻中断,则通过使用 toCharArray() 已经枚举了整个字符串 nad 复制了所有字符。如果绳子很大的话,那就很贵了……
Actually that is bad because it
A lot of unnecessary work...
That's because strings are immutable, and giving out a pointer to its internal array is not allowed, so ToCharArray() makes a copy instead of a cast.
That is:
you can enumerate a string as a char[] but:
you cannot:
If you would go enumerating and would want to break at some point, by using the toCharArray() would already have enumerated the whole string nad made a copy of all chars. If the string would be very big, that is quite expensive...