自定义泛型类

 class CarCollection<T> : IEnumerable<T> where T:Car
    {
        //如果需要用foreach 必须实现 IEnumerable
        // where T:Car  T必须是car或者其子类;如果没有where 则没有类型的限制
        List<T> list = new List<T>();

        public void Add(T t)
        {
            list.Add(t);
        }

        #region IEnumerable<T> 成员

        public IEnumerator<T> GetEnumerator()
        {
            return list.GetEnumerator();
        }

        #endregion

        #region IEnumerable 成员

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return list.GetEnumerator();
        }

        #endregion
    }

 

class Car
    {
        public string PetName;
        public int Speed;

        public Car(string name, int currentSpeed)
        {
            PetName = name;
            Speed = currentSpeed;
        }
        public Car() { }  

    }

 

 class TrunckCar:Car
    {

        public TrunckCar(string name)
        {
            PetName = name;
        }
    }

 

 

main()

{

 CarCollection<Car> cc = new CarCollection<Car>();
            cc.Add(new TrunckCar("aaa"));
            cc.Add(new Car("aaa",12));
            cc.Add(new TrunckCar("bbb"));
            foreach (Car c in cc)
            {
                Console.WriteLine(c.PetName);
            }

}

你可能感兴趣的:(自定义)