using System; using System.Collections.Generic; using System.Linq; using System.Text;namespace test { class Program {
static void Main(string[] args) { Vehlcle v; Car c; v = new Vehlcle(); c = new Car(); v.drive(); c.drive(); v = c; v.drive(); Console.ReadLine(); }
} class Vehlcle { public void drive() { Console.WriteLine("Vehlcle:drive"); } } class Car : Vehlcle { public void drive() { Console.WriteLine("Car:drive"); } } }
B b = new B( ) ; A a = b; 父类的对象向子类转换是不可以 父类对像在new出来的时候是父类对像 子类变量引用父类型变量的强制转换是可以的
Vehlcle v; Car c; v = new Vehlcle(); c = new Car(); v = c; ----------- Car 是 Vehcle的子类, 可以转换为父类型。v=c; 隐式转化,具体的说就是 将原来的 New Vehicle()丢掉,将v的引用指向对象c.
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace test
{
class Program
{
static void Main(string[] args)
{
Vehlcle v;
Car c;
v = new Vehlcle();
c = new Car();
v.drive();
c.drive();
v = c;
v.drive();
Console.ReadLine();
}
} class Vehlcle
{
public void drive()
{
Console.WriteLine("Vehlcle:drive");
}
}
class Car : Vehlcle
{
public void drive()
{
Console.WriteLine("Car:drive");
}
}
}
A a = b;
父类的对象向子类转换是不可以
父类对像在new出来的时候是父类对像
子类变量引用父类型变量的强制转换是可以的
Car c;
v = new Vehlcle();
c = new Car();
v = c;
-----------
Car 是 Vehcle的子类, 可以转换为父类型。v=c; 隐式转化,具体的说就是 将原来的 New Vehicle()丢掉,将v的引用指向对象c.
就相当 于 Vehcle v=new Car ();