c#自定义泛型类的实现

闲来无事,自己研究了泛型类的简单的使用,
where表示泛型约束,表示泛型类型中的参数只能是car类型,IEnumerable是一个接口,一个集合要支持FOREAch遍历,
必须实现IEnumerable接口
复制代码 代码如下:

public class Car
    {
        public string PetName;
        public int Speed;
        public Car(string name, int currentSpeed)
        {
            PetName = name;
            Speed = currentSpeed;
        }
        public Car() { }
    }
    public class CarCollection : IEnumerable where T : Car
    {
        private List Tcars = new List();
        //添加
        public void AddCar(T t)
        {
            Tcars.Add(t);
        }
        //获取其中一个
        public T GetCar(int pos)
        {
           return Tcars[pos];
        }
        public int Count()
        {
            return Tcars.Count;
        }
        #region IEnumerable 成员
        public IEnumerator GetEnumerator()
        {
            return Tcars.GetEnumerator();
        }
        #endregion
        #region IEnumerable 成员
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return Tcars.GetEnumerator();
        }
        #endregion
    }

复制代码 代码如下:

 private void button1_Click(object sender, EventArgs e)
        {
            Car car1 = new Car("one", 150);
            Car car2= new Car("two", 50);
            Car car3 = new Car("three", 150);
            CarCollection cars = new CarCollection();
            cars.AddCar(car1);
            cars.AddCar(car2);
            cars.AddCar(car3);
            MessageBox.Show(cars.Count().ToString());
            foreach (Car item in cars)
            {
                MessageBox.Show(item.PetName+"--"+item.Speed.ToString());
            }
        }

你可能感兴趣的:(c#自定义泛型类的实现)