多型性的型別
多型性意味著操作也可以應用於某些其他型別的值。
有多種型別的多型性:
- Ad hoc 多型性:
包含function overloading
。目標是 Method 可以與不同型別一起使用,而不需要通用。 - 引數多型:
是泛型型別的使用。參見泛型 - 子型別:
具有類的目標繼承以概括類似的功能
Ad hoc 多型性
Ad hoc polymorphism
的目標是建立一個方法,該方法可以由不同的資料型別呼叫,而無需在函式呼叫或泛型中進行型別轉換。可以使用不同的資料型別呼叫以下方法 sumInt(par1, par2)
,並且對於每種型別的組合都有一個自己的實現:
public static int sumInt( int a, int b)
{
return a + b;
}
public static int sumInt( string a, string b)
{
int _a, _b;
if(!Int32.TryParse(a, out _a))
_a = 0;
if(!Int32.TryParse(b, out _b))
_b = 0;
return _a + _b;
}
public static int sumInt(string a, int b)
{
int _a;
if(!Int32.TryParse(a, out _a))
_a = 0;
return _a + b;
}
public static int sumInt(int a, string b)
{
return sumInt(b,a);
}
這是一個示例呼叫:
public static void Main()
{
Console.WriteLine(sumInt( 1 , 2 )); // 3
Console.WriteLine(sumInt("3","4")); // 7
Console.WriteLine(sumInt("5", 6 )); // 11
Console.WriteLine(sumInt( 7 ,"8")); // 15
}
分型
子型別是使用來自基類的繼承來概括類似的行為:
public interface Car{
void refuel();
}
public class NormalCar : Car
{
public void refuel()
{
Console.WriteLine("Refueling with petrol");
}
}
public class ElectricCar : Car
{
public void refuel()
{
Console.WriteLine("Charging battery");
}
}
NormalCar
和 ElectricCar
這兩個類現在都有一種加油的方法,但是他們自己的實施。這是一個例子:
public static void Main()
{
List<Car> cars = new List<Car>(){
new NormalCar(),
new ElectricCar()
};
cars.ForEach(x => x.refuel());
}
輸出將如下:
用汽油加油
充電電池