在继承的情况下父类和子类的转换方式:主要演示“is”关键字和“as”关键字
1.如果要求传参可以传此类的子类
2.如果父类的对象是子类可强转
子类(胡萝卜)
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp1 { /// <summary> /// 胡萝卜类 /// </summary> class Carrot : Vegetables { public static void Main(string[] args) { Vegetables c = new Carrot(); if (c is Carrot) {//is关键字:如果转成功则返回true,否则返回false Console.WriteLine("is---->蔬菜类型胡萝卜对象转胡萝卜成功"); } Eggplant e = c as Eggplant;//as关键字:如果转成功返回需要转换的类型,如果失败返回null if (e == null) { Console.WriteLine("as---->胡萝卜转茄子失败"); } Eggplant ee = new Eggplant(); Vegetables vv = ee as Vegetables; if (vv != null) { Console.WriteLine("as--->胡萝卜转蔬菜类成功"); } Eggplant cc = c as Eggplant; if (cc == null) { Console.WriteLine("as--->胡萝卜转茄子类失败"); } if (!(c is Eggplant)) { Console.WriteLine("is--->胡萝卜转茄子类失败"); } } } }
子类(茄子)
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp1 { /// <summary> /// 茄子类 /// </summary> class Eggplant : Vegetables { } }
父类(蔬菜)
using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp1 { /// <summary> /// 蔬菜类 /// </summary> class Vegetables { } }