對象引用可以
隱式
向上轉換為基類引用
顯式
地向下轉換為子類引用
Plant是PositivePlant和NegativePlant的基類
PositivePlant positivePlant = new PositivePlant() { Name = "陽性植物", MinimumSurvivalTemperature = 10 };
//子轉基:隱式
Plant plant = positivePlant;
//Plant plant = (Plant)positivePlant;//正確的寫法
//基轉子:顯式
PositivePlant convertFromPlant = (PositivePlant)plant;
//PositivePlant convertFromPlant = plant;//錯誤的寫法
Console.WriteLine($"positivePlant == plant:{positivePlant == plant}");//true
Console.WriteLine($"positivePlant == convertFromPlant:{positivePlant == convertFromPlant}");//true
//as運算符
Plant plant2 = positivePlant as Plant;
PositivePlant convertFromPlant2 = plant2 as PositivePlant;
Console.WriteLine($"positivePlant == plant2:{positivePlant == plant2}");//true
Console.WriteLine($"positivePlant == convertFromPlant2:{positivePlant == convertFromPlant2}");//true