【问题标题】:Adding new strings to string array in a class constructor在类构造函数中将新字符串添加到字符串数组
【发布时间】:2022-01-16 07:46:55
【问题描述】:

我正在做一项关于处理结构化/半结构化/非结构化数据的作业,我正在通过导入每个戏剧的 txt 文件和一个 xml 来统计莎士比亚戏剧的字数(以了解语言如何随时间变化)索引文件,其中存储有关每个剧本的关键信息,例如编写年份、角色列表等。然后我将从 txt 中删除角色名称、设置、标点符号和常用词(and, but, or, if etc...)文件准备好进行字数统计 - 全部在 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 +=) 发出错误,无法将字符串转换为字符串 []。如何解决这个问题,以便将字符列表捆绑到 Cast 字符串数组中?

【问题讨论】:

  • 我认为在这种情况下,List<string> 是比数组更好的选择

标签: c# arrays xml string type-conversion


【解决方案1】:
public string[] Cast;

上面的行是一个数组的声明,这个数组还没有在任何地方初始化。所以你不能在这里添加任何东西,直到你通知编译器你想用空间来初始化它来存储一定数量的字符串。

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

此行改为尝试对前一个数组执行 += 操作。
这是不可能的,因为没有为能够执行该操作的数组定义运算符,因此您会收到错误

一种非常简单且更好的方法是将您的 Cast 字段声明为 List<string>

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));

使用 List 而不是数组的优势基本上在于,您不需要提前知道要在数组中存储多少个字符串,而是列表动态扩展其内部存储以容纳新条目。

【讨论】:

  • 我明白了!老实说,我从来没有真正探索过列表和数组之间的区别,难道你不知道我可以访问的任何网站详细解释了 2 吗?如果没有,请不要担心,感谢您回答我的问题:)
猜你喜欢
  • 1970-01-01
  • 2023-01-19
  • 1970-01-01
  • 1970-01-01
  • 2012-12-15
  • 1970-01-01
  • 2014-11-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多