【问题标题】:c# storing reversed string into another stringc#将反转的字符串存储到另一个字符串中
【发布时间】: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# 行为的见解来更好地回答您的问题

标签: c# arrays string reverse


【解决方案1】:

为什么第 2 块有效而第 3 块无效??

块 2 使用接受 char 数组的 constructor of string。这是 Microsoft 提供的现有构造函数,用于形成新字符串

块 3 需要在 char 数组和字符串之间定义隐式转换,因为 Reverse().ToArray() 的输出是 char 数组,而不是字符串。重要的是要理解字符串可以被视为IEnumerable<char>,并且您可以在它们上运行Reverse之类的LINQ方法,但是因为它们在进入的过程中被视为char序列,所以它们作为char序列出现,而不是字符串。您不能直接将 char 数组分配给字符串变量,因为 Microsoft 没有提供此类转换

您可能会发现this discussion on SESE 有趣且相关

脚注;您问为什么不能在 char 数组上调用 ToString - 再次,char[] 上没有 ToString 的重载将 char 数组转换为字符串,因为 Microsoft 没有提供。

有很多方法可以将char[] 变成string(您的第 2 块是理想的),Microsoft 不需要花费时间和精力来制作另一个,而且您还必须考虑可能那里的代码依赖 someCharArray.ToString() 返回System.Char[] - 不是每个人都知道你可以做myObject is char[],他们可能已经做了myObject.ToString == "System.Char[]" 来检查对象是否是一个字符数组。

每当使用新功能升级语言时,都会调查新功能可能导致的所有问题。将.ToString() 添加到从字符生成字符串的char[] 并让它静默(因为它不会导致编译错误)破坏全球数百万个代码库的风险太大了,当有对你已经可以做的事情没有任何好处:

var chars = new[]{'H','e','l','l','o',' ','W','o','r','l','d'}

var s = chars.ToString();     //produces "System.Char[]"
var s = new string(chars);    //produces "Hello World"
                         ^
                  one extra keystroke

使用构造函数版本只需要多击一次键,如果你使用现代 c# 不需要在 new 之后说明类型,只要类型在另一边,它甚至比旧的更短var 版本太 :)

var s = chars.ToString();
string s = new(chars);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多