【问题标题】:Trying to Create an array holding a Struct?试图创建一个包含结构的数组?
【发布时间】:2012-07-30 06:04:25
【问题描述】:

我试图让一个数组保存一个包含两个元素的结构,以保存一个 Xml 标记名称及其值。

我想让数组像这样工作:

MyArrayStruct[Count].TagName = "Bla Bla";  
MyArrayStruct[Count].TagValue = "Bla Bla Bla";

请帮我解决这个问题。


public struct TagContents
{
     String TagName;
     String TagValue;        
};

我在将 Array 声明为 Struct 以使其按我想要的方式工作时遇到问题,我的工作方式就像注释掉的代码一样。

public void LoadXML()
{
    if (File.Exists("Data.xml"))
    {
        //Readin XML
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("Data.xml");
        XmlNodeList dataNodes = xmlDoc.SelectNodes("//FieldData");
        //Count the nodes
        int Max = 0;
        foreach (XmlNode node in dataNodes)
        {
            Max = Max + 1;
        }

        int Count = 0;
        //TagContents MyXmlPointer = new TagContents();
        // MyXmlPointer[] ArrayNode;
        //  ArrayNode = new MyXmlPointer[Max];

        foreach (XmlNode node in dataNodes)
        {
            // ArrayNode[Count].TagName =node.SelectSingleNode("Have not found what to put here yet but will get there").Name;
            // ArrayNode[Count].TagValue =node.SelectSingleNode("Have not found what to put here yet but will get there").InnerText;                      
        }
    }
    else
    {
        MessageBox.Show("Could not find file Data.xml");
    }
}

【问题讨论】:

  • 我的注释部分是我希望它做的,但这不起作用

标签: c# .net arrays class struct


【解决方案1】:

制作字段public:

public class TagContent
{
    public String TagName;
    public String TagValue;
};

并使用它,我建议使用泛型(如List<>):

var tags = new List<TagContent>();

tags.Add(new TagContent{TagName = "aaa", TagValue = "vvv"});

// use it:
// get value of 'TagName' of item 5:
var tagname5 = tags[5].TagName;

【讨论】:

  • 结构数组通常比List&lt;&gt; 结构好得多,因为字段可以在数组元素中直接访问,但不能在List&lt;&gt; 元素中直接访问。
猜你喜欢
  • 2021-08-05
  • 1970-01-01
  • 1970-01-01
  • 2011-07-13
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多