C# 文法練習(10): 類[二] – 繼承、覆蓋、多態、隱藏

來源:互聯網
上載者:User
繼承:
using System;class Parent{    public void Msg() { Console.WriteLine("Parent"); }}class Child : Parent { }class Program{    static void Main()    {        Parent ObjParent = new Parent();        Child ObjChild = new Child();        ObjParent.Msg(); //Parent        ObjChild.Msg();  //Parent        Console.ReadKey();    }}

覆蓋:

using System;class Parent{    public virtual void Msg() { Console.WriteLine("Parent"); }}class Child : Parent {    public override void Msg() { Console.WriteLine("Child"); }}class Program{    static void Main()    {        Parent ObjParent = new Parent();        Child ObjChild = new Child();        ObjParent.Msg(); //Parent        ObjChild.Msg();  //Child        Console.ReadKey();    }}

多態:

using System;class Parent{    public virtual void Msg() { Console.WriteLine("Parent"); }}class Child1 : Parent {    public override void Msg() { Console.WriteLine("Child_1"); }}class Child2 : Parent{    public override void Msg() { Console.WriteLine("Child_2"); }}class Program{    static void Main()    {        Parent Obj1 = new Child1();        Parent Obj2 = new Child2();        Obj1.Msg(); //Child_1        Obj2.Msg(); //Child_2        Console.ReadKey();    }}

隱藏:

using System;class Parent{    public void Msg() { Console.WriteLine("Parent"); }}/* 有意隱藏應使用 new 關鍵字 */class Child1 : Parent {    new public void Msg() { Console.WriteLine("Child_1"); }}/* 無意隱藏會有提示, 但可用 */class Child2 : Parent{    public void Msg() { Console.WriteLine("Child_2"); }}class Program{    static void Main()    {        Parent Obj1 = new Child1();        Parent Obj2 = new Child2();        Child1 Obj3 = new Child1();        Child2 Obj4 = new Child2();        Obj1.Msg(); //Parent        Obj2.Msg(); //Parent        Obj3.Msg(); //Child_1        Obj4.Msg(); //Child_2        Console.ReadKey();    }}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.