【问题标题】:Error: Cannot implicitly convert type 'string' to 'string[]'?错误:无法将类型“字符串”隐式转换为“字符串 []”?
【发布时间】:2018-04-29 22:20:30
【问题描述】:

我试图创建一个数组,使用一个包含单词的 .txt 文件。每个数组只有一个字。但是在那里,fajlbe.ReadLine(); 被固定为错误代码。为什么?

struct Sor
{
    public string árucikk;
}
static Sor[] TSor = new Sor[1000];

static void Main(string[] args)
{
    StreamReader fajlbe = new StreamReader("penztar.txt");
    string[] tomb = new String[1];

    int n = 0;

    while(!fajlbe.EndOfStream)
    {
        tomb = fajlbe.ReadLine();   //here I've got an error
        TSor[n].árucikk = tomb[0];
        n++;
    }
    Console.WriteLine(TSor[1]);

    fajlbe.Close();

【问题讨论】:

  • 你能把错误贴出来吗?
  • 如你在标题中看到的,错误是“Cannot implicitly convert type 'string' to 'string[]'”
  • 提示:ReadLine 返回 string 而不是 string[]
  • 意图不明确......我读它的一种方式是你想分割每一行,这样你就得到了一个“单词”数组。此外,您可能只想使用ReadAllLines()。见stackoverflow.com/questions/4220993/…

标签: c# arrays string


【解决方案1】:
tomb = fajlbe.ReadLine();

ReadLine 方法返回一个字符串,而变量 tomb 被声明为一个字符串数组 (string[] tomb = new String[1];)。您不能将字符串分配给字符串数组。

相反,如果您打算将字符串分配给数组的第一个元素,您可以通过设置数组的第一个元素来做到这一点:

tomb[0] = fajlbe.ReadLine();

这里似乎不需要数组。如果是这样,您可以简单地将变量 tomb 的声明更改为将其声明为字符串:

string tomb = string.Empty;

当然你需要改变,

TSor[n].árucikk = tomb[0];

到,

TSor[n].árucikk = tomb;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 2014-05-15
    • 2014-02-04
    相关资源
    最近更新 更多