C#中ArrayList类定义的数组 如何访问数组里的元素??

定义了一个类VNode
class VNode
{
private string data;
private ArcNode firstarc;

public VNode() //构造函数
{
data = null;
firstarc = null;
}

public string Data //顶点属性
{
get
{
return data;
}
set
{
data = value;
}
}
}

现在在另一个类里用ArrayList定义一个数组 adjList, 这个数组中每个元素类型都是VNode
adjList = new ArrayList();
一开始要求数组是空的,执行时会动态添加VNode类型的数组元素
现在一个函数中要访问这个数组元素的Data属性 请问该如何访问?

1. 需强制转换成 你想要的类型

2. 示例代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList lst =new ArrayList(){ 2, 3, 4, 5 };

            //访问其元素值,强制转换
            for (int i = 0; i < lst.Count; i++)
            {
                Console.WriteLine((int)lst[i]);
            }

            Console.Read();
        }
    }
}

3. 运行结果如下:

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-09-07
只能通过下标访问 比如 adjList[index]

如果要找到Data属性相同的,只能遍历adjList,通过判断返回

ArrayList本身就是一个链表结构,不可能直接访问到其中的元素

如果想通过键直接访问到值,可以考虑用Dictionary

顺便提一句,在开发中已经不再使用ArrayList,而使用泛型类List<T>本回答被提问者采纳
第2个回答  2011-08-11
正如,刚才你所说的 “一开始要求数组是空的,执行时会动态添加VNode类型的数组元素”,你要在得到ArrayList数组之前 ,必须保证你的数组必须有资料,如果有了就可以查找,如:
VNode a = (VNode) adjList [ 1 ];
第3个回答  2011-08-11
for(int i=0;i<adjList.Count;i++)
{
VNode a = (VNode) adjList[i];
Response.Write(a.Data);
}
第4个回答  推荐于2017-10-04
ArrayList myAL = new ArrayList();
myAL.Add("Hello");
myAL.Add("World");
myAL.Add("!");

Console.Write(myAL[1].ToString());

foreach (string tt in myAL)
{
Console.Write(tt);
}

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网