C#基礎知識(八)泛型
泛型的好處很多,包括複用性(可供多個型別使用而不用每個型別都定義一次),型別安全(不合法的型別報錯),高效率(減少裝箱和拆箱)
舉例:
假設我們有一個父類Animal,所有動物繼承這個類,現在需要做一個比較動物重量的方法,如果不用泛型,則我們隊沒類動物都需要過載一次比較的方法:
public class Animal
{
public int Weight { get; set; }
public int MaxWeight(Car other) // 貓和其他動物比較
{
return Math.Max(this.Weight, other.Weight);
}
public int MaxWeight(Dog other) //狗和其他動物比較
{
return Math.Max(this.Weight, other.Weight);
}
}
public class Car : Animal
{}
public class Dog : Animal
{}
如果我們接下來還要增加其他的動物,則還需要寫一次方法。
而我們使用泛型則很簡單:
public class Animal
{
public int Weight { get; set; }
public int MaxWeight<T>(T other) where T : Animal
{
return Math.Max(this.Weight, other.Weight);
}
}
public class Car : Animal
{}
public class Dog : Animal
{}
只要是繼承Animal的動物全部可以進行比較