閱讀38 返回首頁    go 阿裏雲 go 技術社區[雲棲]


C#自定義泛型

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

namespace CustomGenericCollection
{
    #region 汽車的定義
    public class Car
    {
        public string PetName;
        public int Speed;

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

    public class SportsCar : Car
    {
        public SportsCar(string p, int s)
            : base(p, s) { }
        // 其他方法
    }

    public class MiniVan : Car
    {
        public MiniVan(string p, int s)
            : base(p, s) { }
        // 其他方法
    }
    #endregion

    #region 自定義泛型集合
    public class CarCollection<T> : IEnumerable<T> where T : Car//:下麵的泛型集合類的項目必須是Car 或Car的繼承類
    {
        private List<T> arCars = new List<T>();
        public T GetCar(int pos)
        {
            return arCars[pos];
        }
        public void AddCar(T c)
        {
            arCars.Add(c);
        }
        public void ClearCars()
        {
            arCars.Clear();
        }
        public int Count
        {
            get { return arCars.Count; }
        }
        // IEnumerable<T>擴展自IEnumerable的,因此,我們需要實現的GetEnumerator()方法的兩個版本。
        System.Collections.Generic.IEnumerator<T> IEnumerable<T>.GetEnumerator()
        {
            return arCars.GetEnumerator();
        }

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

        public void PrintPetName(int pos)
        {
            Console.WriteLine(arCars[pos].PetName);
        }
    }
    #endregion

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***** Custom Generic Collection *****\n");
            CarCollection<Car> myCars = new CarCollection<Car>();
            myCars.AddCar(new Car("Rusty", 20));
            myCars.AddCar(new Car("Zippy", 90));

            foreach (Car c in myCars)
            {
                Console.WriteLine("PetName: {0}, Speed: {1}", c.PetName, c.Speed);
            }
            Console.WriteLine();

            // CarCollection<Car> can hold any type deriving from Car.
            CarCollection<Car> myAutos = new CarCollection<Car>();
            myAutos.AddCar(new MiniVan("Family Truckster", 55));
            myAutos.AddCar(new SportsCar("Crusher", 40));
            foreach (Car c in myAutos)
            {
                Console.WriteLine("Type: {0}, PetName: {1}, Speed: {2}",
                  c.GetType().Name, c.PetName, c.Speed);
            }

            Console.ReadLine();
        }
    }
}

最後更新:2017-04-02 22:16:20

  上一篇:go 如何手工卸載和安裝NTKO OFFICE文檔控件
  下一篇:go 『每日一題 2012-02-10』猴子選大王問題 C語言實現