我正在做一個關于處理結構化/半結構化/非結構化資料的作業,我正在通過匯入每個劇本的 txt 檔案和一個 xml 索引檔案來計算莎士比亞戲劇的字數(以查看語言如何隨時間變化)存盤有關每個劇本的關鍵資訊,例如撰寫年份,角色串列等。字數統計 - 全部在 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 字串陣列中?
uj5u.com熱心網友回復:
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 而不是陣列的優點基本上在于您不需要提前知道要在陣列中存盤多少個字串,而是串列動態擴展其內部存盤以容納新條目。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/379713.html
上一篇:如何在Xpath1.0中使用函式
