1、转型分为向上转型和向下转型
街上看见一只狗,说狗是一个动物,这肯定成立,也就是所说的向上转型
2、向上转型
class Animal { }
class Dog : Animal {}
class Hashiqi : Dog { }
public class Program {
//Dog d = new Dog();
//Animal a = d;
Animal a = new Dog();
}
(1)解释:父类的引用可以指向子类的对象 或叫 由子类类型转换为父类类型;
是一个隐式转换,不需要额外的操作;
向上转型肯定会成功;
向上转型的对象将不在能够使用子类中特有的字段属性和方法 ,只能使用父类中共有的部分
class Animal {
public string name;
public int age;
}
class Dog : Animal {
public char gender;
}
class Hashiqi : Dog {
public string kind;
}
public class Program {
//实例化一个Dog对象
Dog d = new Dog();
d.name = " ";
d.age = 10;
d.gender = ' ';
// d.kind = ""; d.kind不行,kind是子类hashiqi的,不能访问
//向上转型
Animal a = d;
//Animal a = new Dog();
a.name = " ";
a.age = 10;
// a.gender = ' '; a.gender不行
//所以向上转型的对象将不在能够使用子类中特有的字段属性和方法 ,只能使用父类中共有的部分
}
(2)多态应用示例(//public Class 的类中 不可以引用非 public 的类(Class))
class Animal {}
class Dog : Animal {}
class Hashiqi : Dog {}
class Wo1f : Animal { }
class Tiger : Animal { }
class Lion : Animal { }
class Panda : Animal { }
class Monkey : Animal { }
class Snake : Animal { }
//public 的类中 不可以引用非 public 的类Class
class Test : MonoBehaviour
{
private void Awake()
{
// 多态的应用
RecordAnimal(new Monkey() );
}
//应用示例
//录入所有动物信息
//方法1:重载
//public void RecordAnimal(Monkey m) { }
//public void RecordAnimal(Snake s) { }
//......
//方法2:多态
public void RecordAnimal(Animal a) { }
}
3、向下转型
class Animal {}
class Dog : Animal {}
public class Program {
Dog d = new Animal() as Dog ;
}
(1)解释:由父类类型转型为子类类型
是一个显示转换,需要强制转换类型,推荐使用 as
转型的过程肯能会出错 所以需要额外的操作 ,强制类型转换
as只能用在引用数据类型上,不能用在基本数据类型(如 int)
如果向下转型失败,则得到 null
向下转型不一定成功,所以在做向下转型前,一定要先用is判断下类型
向下转型后的对象就可以使用子类中特有的字段属性和方法,前提条件是要转型成功才可以
class Animal {}
class Dog : Animal {}
class Hashiqi : Dog {}
class Program {
// Dog d = new Animal(); //错误,不做强制转换会报错
// Dog d =(Dog ) new Animal(); //方法1
Dog d = new Animal() as Dog ; //方法2 推荐 as只能用在引用数据类型上,不能用在基本数据类型(如 int)
// Debug.Log(d) //null
//上述方法会转型失败,得到的 d 为 null ;
}
(2) 如何转型成功?
class Animal {}
class Dog : Animal {}
class Hashiqi : Dog {}
public class Program {
private void Awake()
{
Animal a = new Dog();
//如何转型成功
Dog e = a as Dog; //此时的e 不为 null
}
}
(3) 向下转型成功后的对象可以使用子类中特有的字段属性和方法。
class Animal {
public string name;
public int age;
}
class Dog : Animal {
public char gender;
}
class Hashiqi : Dog {
public string kind;
}
class Program
{
private void Awake()
{
/*
//实例化一个Dog对象
Dog d = new Dog();
d.name = " ";
d.age = 10;
d.gender = ' ';
// d.kind = ""; d.kind不行,kind是子类的,不能访问
//向上转型
Animal a = d;
a.name = " ";
a.age = 10;
// a.gender = ' '; a.gender不行
//所以向上转型的对象将不在能够使用子类中特有的字段属性和方法 ,只能使用父类中共有的部分
*/
Animal a = new Dog();
//向下转型
Dog dd = a as Dog;
dd.gender = ' '; //向下转型后的对象就可以使用子类中特有的字段属性和方法,前提条件是要转型成功才可以
//转型失败
Hashiqi h = a as Hashiqi;
h.kind = " "; //此时虽然程序不报错 但是此时转型失败 因为此时 h 是 null
}
//如何判断 a到底是什么类型?
public void AnimalKind(Animal a)
{
if (a is Hashiqi )
{
Debug.Log("hashiqi");
}
}
}