namespace Lesson15_继承_万物之父和装箱拆箱 { #region 里氏替换原则知识点回顾 //概念:父类容器装子类对象 //作用:方便进行对象存储和管理 //使用 //is和as //is用于判断 //as用于转换 class Father { } class Son : Father { public void Speak() { Console.WriteLine("Son.Speak()"); } } #endregion #region 知识点一 万物之父 //万物之父 //关键字Object //概念 //object时所有类型的积累,他是一个类(引用类型) //作用: //1.可以利用里氏替换原则,用object容器装所有对象 //2.可以用来表示不确定类型,作为函数参数类型 #endregion internal class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); #region 知识点二 万物之父的使用 Father f = new Son(); if (f is Son) { (f as Son).Speak(); } //引用类型 object o = new Son(); o = f; //用is和as来判断和转换即可 if(o is Son) { (o as Son).Speak(); } //值类型 object o2 = 1f; //用强转 float fl = (float)o2; Console.WriteLine(o2); //特殊的string类型 object str = "123"; string str2 = str.ToString(); string str3 = str as string; Console.WriteLine(str2+str3); //数组 object arr = new int[10]; int[] ar = arr as int[]; #endregion #region 知识点三 装箱拆箱 //发生条件 //用objcet存值类型(装值) //再把object转为值类型(拆箱) //装箱 //把值类型用引用类型存储 //栈内存会迁移到堆内存中 //拆箱 //把引用类型存储的值类型取出来 //堆内存会迁移到栈内存中 //好处:不确定类型时可以方便参数的存储和传递 //坏处:存在内存迁移,增加性能消耗 #endregion Test2(1, 2, 3, 4); } #region 知识点四 无敌知识点 //在使用变长传值时,如果不知道会传什么进去的时候就可以用object来存储 static void Test(params int[] array) { }//这个方法只能获取int类型 static void Test2(params object[] array) { }//这样就可以存任意长度任意类型的参数进来了 #endregion } }