提问者:小点点

向类构造函数中的字符串数组添加新字符串


我正在做一项关于使用结构化/半结构化/非结构化数据的作业,我正在对莎士比亚的戏剧进行字数统计(以了解语言如何随时间变化),方法是导入每部戏剧的txt文件和xml索引文件,该文件存储有关每部戏剧的关键信息,如编写年份、角色列表等。。然后,我将删除字符名、设置、标点符号和常用词(和、但、或,如果等…)从txt文件准备好进行字数统计-全部在C#中运行的控制台脚本中。我正在编写一个类,每个剧本的数据都将存储在这个类中,目前看起来是这样的:

    class PlayImport
{
    public string Title;
    public DateTime Year;
    public string location;
    public string[] Cast;
    public Counter[] WordCount;

    public PlayImport(string location, int Num)
    {
        XmlDocument Reader = new XmlDocument();
        Reader.Load(location);
        this.Title = Convert.ToString(Reader.DocumentElement.ChildNodes[Num].Attributes["Title"].Value);
        this.Year = Convert.ToDateTime(Reader.DocumentElement.ChildNodes[Num].Attributes["Year"].Value);
        this.location = Convert.ToString(Reader.DocumentElement.ChildNodes[Num].Attributes["Location"].Value);
        foreach (XmlNode xmlNode in Reader.DocumentElement.ChildNodes[Num].ChildNodes[0].ChildNodes)
            this.Cast += Convert.ToString(xmlNode.Attributes["Name"].Value);
    }
}

然而,最后一行(Cast=)给出了一个错误,不能将string转换为string[]。如何绕过这个问题,使字符列表捆绑在一起进入Cast字符串数组?


共1个答案

匿名用户

public string[] Cast;

上面的一行是一个数组的声明,这个数组还没有在任何地方初始化。因此,在您通知编译器您想用存储一定数量字符串的空间初始化它之前,您不能在这里添加任何内容。

....
this.Cast += Convert.ToString(xmlNode.Attributes["Name"].Value);

相反,此行尝试在上一个数组上执行=操作
这是不可能的,因为没有为能够执行该操作的数组定义运算符,因此会出现错误

一种非常简单且更好的方法是将Cast字段声明为列表

public List<string> Cast = new List<string>();

然后在foreach中,只需向现有字符串集合添加一个新字符串

foreach (XmlNode xmlNode in Reader.DocumentElement.ChildNodes[Num].ChildNodes[0].ChildNodes)
   this.Cast.Add(Convert.ToString(xmlNode.Attributes["Name"].Value));

使用列表而不是数组的优点基本上是,您不需要事先知道要在数组中存储多少字符串,而是列表自动扩展其内部存储以容纳新条目。