基础知识一:
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace WindowsFormsApplication2 { public class ParentClass { public ParentClass() { } public string NamePropety { get; set; } public string GetName() { return ""; } } public class ChildClass : ParentClass { public ChildClass() { } public int Age { get; set; } public int GetAge() { return 10; } } static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { //=>1、实例化父类 ParentClass parent = new ParentClass(); string _NamePropety = parent.NamePropety; string _name = parent.GetName(); //1.1向上转型 子类转父类 ParentClass parent1 = new ChildClass(); //或者ParentClass parent1 = new ChildClass() as ParentClass; string _NamePropety1 = parent1.NamePropety; string _name1 = parent1.GetName(); //=>2、实例化子类 ChildClass child = new ChildClass(); string _NamePropety2 = child.NamePropety; string _name2 = child.GetName(); int ageName2 = child.GetAge(); int age2 = child.Age; //2.1向下转型 父类转换子类。 ParentClass child3 = new ChildClass(); ChildClass child4 = (ChildClass)child3; string _NamePropety3 = child4.NamePropety; string _name3 = child4.GetName(); int ageName3 = child4.GetAge(); int age3 = child4.Age; //=>3、不正确的父类转子类。 //as方式转换。(as 转换失败时,程序不会抛异常,child1对象为NULL。) ChildClass child1 = new ParentClass() as ChildClass; //或者 ChildClass child1 = (ChildClass)new ParentClass(); Console.WriteLine(child1.NamePropety); //强制转换。(程序会抛出异常。) ChildClass child1_1 = (ChildClass)new ParentClass(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }