c custom generic class implementation

  • 2020-05-12 03:09:15
  • OfStack

Be free and at leisure, who has researched the simple use of generic classes,
where is a generic constraint, which means that the parameters in a generic type can only be of type car, IEnumerable is an interface, and a collection should support FOREAch traversal,
The IEnumerable interface must be implemented

public class Car
    {
        public string PetName;
        public int Speed;
        public Car(string name, int currentSpeed)
        {
            PetName = name;
            Speed = currentSpeed;
        }
        public Car() { }
    }
    public class CarCollection<T> : IEnumerable<T> where T : Car
    {
        private List<T> Tcars = new List<T>();
        // add 
        public void AddCar(T t)
        {
            Tcars.Add(t);
        }
        // To obtain the 1 a 
        public T GetCar(int pos)
        { 
           return Tcars[pos];
        }
        public int Count()
        {
            return Tcars.Count;
        }
        #region IEnumerable<T>  Members of the 
        public IEnumerator<T> GetEnumerator()
        {
            return Tcars.GetEnumerator();
        }
        #endregion
        #region IEnumerable  Members of the 
        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<Car> cars = new CarCollection<Car>();
            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());
            }
        }

Related articles: