循环遍历对象C#的ArrayList

时间:2016-10-07 11:08:33

标签: object arraylist

我正在尝试遍历类型(人)的对象的数组列表,所以我创建了两个类:

Person.cs

using System;

namespace GenericTypes
{
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public DateTime DateTime { get; set; }

    }
}

People.cs

using System;
using System.Collections;
using System.Collections.Generic;

namespace GenericTypes
{
    public class People
    {
        public ArrayList GetNonGenericPeople()
        {
            var people = new ArrayList()
            {
                new Person() {FirstName = "Djerah", LastName = "Ahmed Rafik", Age = 23, DateTime = DateTime.Today},
                new Person() {FirstName = "Djerah", LastName = "Amjed Amir", Age = 11, DateTime = DateTime.Today},
                new Person() {FirstName = "Gadda", LastName = "Anoir", Age = 25, DateTime = DateTime.Today}

            };
            return people;
        }

        public  List<Person> GetGenericPeople()
        {
            var people = new List<Person>()
            {
                new Person() {FirstName = "Djerah", LastName = "Ahmed Rafik", Age = 23, DateTime = DateTime.Today},
                new Person() {FirstName = "Djerah", LastName = "Amjed Amir", Age = 11, DateTime = DateTime.Today},
                new Person() {FirstName = "Gadda", LastName = "Anoir", Age = 25, DateTime = DateTime.Today}

            };

            return people;
        }
    }
}

我无法弄清楚如何循环 GetNonGenericPeople()所以我可以用它的属性输出每个对象

Program.cs的

namespace GenericTypes
{
    class Program
    {
        static void Main(string[] args)
        {
           var persons = new People();
            var p = persons.GetNonGenericPeople();

            foreach (var s in p)
            {
                Console.WriteLine(s);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

尝试使用过滤掉 OfType<T>()个实例的T Linq ;另一个选项是Cast<T>(),试图投射每个项目(如果投射失败则抛出异常)

 foreach (var s in p.OfType<Person>()) {
   ...
 }