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<T> : IEnumerable<T> where T : Car
{
private List<T> Tcars = new List<T>();
//添加
public void AddCar(T t)
{
Tcars.Add(t);
}
//获取其中一个
public T GetCar(int pos)
{
return Tcars[pos];
}
public int Count()
{
return Tcars.Count;
}
#region IEnumerable<T> 成员
public IEnumerator<T> 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<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());
}
}