【发布时间】:2022-01-15 15:49:34
【问题描述】:
block1 有效:-
String input = "The quick brown fox jumps over the lazy dog";
char[] output = input.Reverse().ToArray();
Console.WriteLine(output);
当我尝试将输出存储到新字符串中时,block2 也可以:-
String input = "The quick brown fox jumps over the lazy dog";
char[] output = input.Reverse().ToArray()
String output2 = new String(output);
Console.WriteLine(output2);
但是当我尝试将输出存储到字符串中时,block3 不起作用:-
String input = "The quick brown fox jumps over the lazy dog";
char[] output = input.Reverse().ToArray()
String output2 = output; //I tried to use convert.ToString() as well, but it didn't work
Console.WriteLine(output2);
为什么区块 2 有效而区块 3 无效??
【问题讨论】:
-
输出是
char[],输出2是string。您需要将 char[] 转换为字符串。对于 block2,您使用字符串构造函数来执行此操作。 stackoverflow.com/questions/1324009/… -
在 c# 中,我们不能直接从 char[] 分配字符串,字符串使用内部 char[] 并且是不可变的。您必须使用
new String(charBuffer);语法。直接写入字符串的唯一方法是使用不安全的代码,不推荐这样做。 -
块 3 将导致编译器出现错误消息。不清楚的信息是什么?我很想知道,因此我们可以使用从中获得的关于您如何看待 C# 行为的见解来更好地回答您的问题