2017-04-21 98 views
0
public class vehicles 
{ 
    public string name = "genreal"; 
    public string category = "general"; 
    public virtual void type() 
    { 
     Console.WriteLine(" my name is " + name + " my category is " + category + " I am from Vehicles class"); 
    } 
} 

public class bike : vehicles 
{ 
    public override void type() 
    { 
     name = "Honda"; 
     category = "Bike"; 
     Console.WriteLine("my name is " + name + " my category is " + category + " I am from Bike class"); 
    } 
} 

public class Car : vehicles 
{ 
    public override void type() 
    { 
     name = "Suzuki"; 
     category = "Car"; 
     Console.WriteLine(" my name is " + name + " my category is " + category + " I am from car class"); 
    } 
} 

這是我的類彼此繼承現在我正在嘗試調用派生類的方法。我們都知道polymorhpism使您能夠在運行時通過基類refrence變量調用派生類方法。但我在這裏做一點變化我正在使用父類refrence變量和父類對象調用它鑄造無法投射'polymorphism.vehicles'類型的對象來鍵入'polymorphism.Car

vehicles V = new vehicles(); 
((Car)V).type(); 
Console.ReadLine(); 

這是給予例外Unable to cast object of type 'polymorphism.vehicles' to type 'polymorphism.Car' 難道是因爲我們不能投父CLAS反對子類?我不確定請引導我

+0

正確。您不能將父類轉換爲子類(除非具體類實際上是派生類型) – john

回答

0

您不能從父類轉換子類。 您需要創建var當成Car並從那裏你可以訪問Car方法

Car c = new Car(); 
c.type(); 

從那裏,你可以訪問父的屬性和孩子的。

相關問題