C#裡式轉化應用
阿新 • • 發佈:2018-11-19
裡式轉化:
1>子類可以賦值給父類;如果一個地方需要父類作為引數,可以找一個子類物件代替
2>如果父類中裝的是子類物件,那麼這個父類可以強轉化成子類物件
//Person p=new Student(); //Student ss=(Student)p; // //is的用法: //if(p is Student) { //Student ss = (Student)p; //ss.StudentSayHello(); } //as 的用法: //Student t=p as Student; //if (s != null) //{ //t.StudentSayHello(); // }
應用例項:
結果:
程式碼如下:
//子類均繼承父類,所以可以建立一個父類陣列,可以放所有子類的物件 Person[] prs = new Person[10]; //產生隨機10個數,對於數字不同用不同的子類函式 Random r = new Random(); for (int i = 0; i < prs.Length; i++) { int n = r.Next(1, 5); //next(MinValue,MaxValue);返回指定範圍的隨機數 switch (n) { case 1: prs[i] = new Student();//子類物件賦值給父類 break; case 2: prs[i] = new Teacher(); break; case 3: prs[i] = new Meinv(); break; case 4: prs[i] = new Person(); break; } } //prs中存放10個物件(子類,父類) for (int i = 0; i < prs.Length; i++) { if (prs[i] is Meinv)//第二點,父類中有子類的物件 { Meinv mn = (Meinv)prs[i]; mn.MeinvSayHi(); } else if (prs[i] is Student) { Student s = (Student)prs[i]; s.StudentSayHi(); } else if (prs[i] is Teacher) { Teacher t = (Teacher)prs[i]; t.TearcherSayHi(); } else { prs[i].PersonSayHi(); } } Console.ReadKey(); } }