基類、子類之間的類型轉換


對象引用可以
隱式向上轉換為基類引用
顯式地向下轉換為子類引用

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

示例代碼

BaseAndSubClassTypeConversion

參考資料

C# 轉換


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM