首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

大家看一个关于ArrayList的一个有关问题

2013-05-02 
大家看一个关于ArrayList的一个问题using Systemusing System.Collections.Genericusing System.Linqus

大家看一个关于ArrayList的一个问题

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

namespace CollectionDemo
{
    class Student
    {
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private int id;

        public int Id
        {
            get { return id; }
            set { id = value; }
        }
    }
}

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

namespace CollectionDemo
{
    class Teacher
    {
        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private int id;

        public int Id
        {
            get { return id; }
            set { id = value; }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace CollectionDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Student s1 = new Student();
            Student s2 = new Student();
            Teacher t1 = new Teacher();
            Teacher t2 = new Teacher();
            s1.Name = "dwyane";
            s1.Id = 1;
            s2.Name = "lebron";
            s2.Id = 2;


            t1.Name = "paul";
            t1.Id = 3;
            t2.Name = "kobe";
            t2.Id = 4;

            ArrayList list = new ArrayList(5);
            list.Add(s1);
            list.Add(s2);
            list.Add(t1);
            list.Add(t2);

            foreach (Object o in list)
            {
                if (o is Student)
                {
                    Console.WriteLine(((Student)o).Name+"\t"+((Student)o).Id);
                }
                else
                {
                    Console.WriteLine(((Teacher)o).Name + "\t" + ((Teacher)o).Id);
                }

                Console.ReadLine();
            }
        }
    }
}



为什么只能遍历s1?????
[解决办法]
 foreach (Object o in list)
            {
                if (o is Student)
                {
                    Console.WriteLine(((Student)o).Name+"\t"+((Student)o).Id);
                }
                else
                {
                    Console.WriteLine(((Teacher)o).Name + "\t" + ((Teacher)o).Id);
                }
 
                Console.ReadLine();//没循环一次,就等待你输入一行,你瞧下Enter键盘,或者你将这句话放到循环外面就行了
            }

热点排行