【问题标题】:CS0029 Cannot implicitly convert type 'char' to 'string'CS0029 无法将类型“char”隐式转换为“string”
【发布时间】:2022-07-06 04:25:23
【问题描述】:

CS0029 无法将类型“char”隐式转换为“string”

string text = System.IO.File.ReadAllText(@"C:\x.txt");
        string newText = "";
        string[] words = text.Split(' ');
        int selectedWordNumber = 1;
        string selectedWord = words[selectedWordNumber];
        int selectedLetterNumber = selectedWord.Length - 1;
        while (selectedWordNumber != words.Length)
        {

            foreach (var word in words)
            {

                string newWord = "";
                string selectedLetter = selectedWord[selectedLetterNumber];

错误来自这一行

string selectedLetter = selectedWord[selectedLetterNumber];

如果是乱码,不好意思,我今天才开始学习。

【问题讨论】:

  • 当你索引一个字符串时,你会收到一个char。所以应该是char selectedLetter = selectedWord[selectedLetterNumber];docs.microsoft.com/en-us/dotnet/api/…
  • 感谢@JohnnyMopp 的回复。我更改了它,在调试之前没有错误,但是在运行代码时,我在同一行收到此错误: System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

标签: c#


【解决方案1】:

对字符串使用数组索引会返回char。添加ToString()修复

string selectedLetter = selectedWord[selectedLetterNumber].ToString();

【讨论】:

    猜你喜欢
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-30
    • 1970-01-01
    • 2015-08-07
    • 2017-10-06
    • 2022-08-23
    相关资源
    最近更新 更多