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使您能够在运行时通过基类转换变量调用派生的类方法。但是我在这里几乎没有更改,我通过使用parent类求和变量和父级对象来调用它
vehicles V = new vehicles();
((Car)V).type();
Console.ReadLine();
这给出了例外Unable to cast object of type 'polymorphism.vehicles' to type 'polymorphism.Car'
是因为我们不能将父氏clas抛在子班上吗?我不确定请指导我
您无法从父班上施放子类。您需要创建VAR作为Car
,然后从那里可以访问Car
方法
Car c = new Car();
c.type();
从那里您可以访问父亲的财产和孩子。