如何访问多维ArrayList的元素. [英] How to access an elements of a multidimensional ArrayList.

查看:83
本文介绍了如何访问多维ArrayList的元素.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一堂课:

We have a class:

class Node
    {
        private string gid;
        private string name;

public Node(string gimid, string ptyname)  // constructor
 {
     gid = gimid;
     name = ptyname;
 }

        public string gmid          // property
        {
            get { return gid; }
            set { gid = value; }
        }

        public string pname         // property
        {
            get { return name; }
            set { name = value; }
        }

}


还有一个将保持表结构上方的ArrayList,用于存储记录,如下所示:


And an ArrayList that will be holding above table’s structure to store records as follows:

ArrayList mapList = new new ArrayList(); 
string FirstElementID = ds.Tables[0].Rows[0]["Pty_id"].ToString();                          string FirstElementName = ds.Tables[0].Rows[0]["Pty_Name"].ToString();    
Node FirstNode = new Node(FirstElementID, FirstElementName);    
 	mapList.Add(FirstNode);                        



现在的问题是如何从该ArrayList访问元素?



Now the question is how to access elements from this ArrayList?

推荐答案

您可以将其重写为

You can rewrite it to

List<Node> mapList = new List<Node>()

foreach (DataRow row in ds.Tables[0].Rows)
{
  mapList.Add(new Node(row["Pty_id"].ToString(), row["Pty_Name"].ToString()));
}



完成后,将元素添加到列表中.您可以根据需要访问,添加,插入和修改列表.

但这与多维数组无关.



And when you are done adding elements to the List. You can access, add, insert and modify the List as needed.

But it has nothing to do with a multidimensional array.


我建​​议您将ArrayList替换为其通用的对等物List<T>,其中T是列表中元素的类型.在您的代码中,该代码将为Node.请在此处阅读: http://en.csharp-online.net/CSharp_Generics_Recipes%E2%80% 94Replacing_the_ArrayList_with_Its_Generic_Counterpart [^ .
这样,当您从该列表中访问元素时,类型将是已知的,并且您可以直接访问所有Node成员,而无需使用强制转换操作.

干杯!
I suggest you replace ArrayList with its generic counterpart List<T> where T is the type of elements in the list. In your code that would be Node. Please read about it here: http://en.csharp-online.net/CSharp_Generics_Recipes%E2%80%94Replacing_the_ArrayList_with_Its_Generic_Counterpart[^].
That way when you access an element from that list the type will already be known and you can access all of Node''s members directly without using a cast operation.

Cheers!


这篇关于如何访问多维ArrayList的元素.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆