zoukankan      html  css  js  c++  java
  • C# 语法练习(10): 类[二] 继承、覆盖、多态、隐藏


    继承:
    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();
        }
    }
    

  • 相关阅读:
    不忘初心,方得始终
    【读书笔记】Windows核心编程
    工作心得
    2015年随记
    微信开发的黑魔法
    [cssTopic]浏览器兼容性问题整理 css问题集 ie6常见问题【转】
    获取微信用户openid
    Spring Boot应用开发起步
    一种在Java中跨ClassLoader的方法调用的实现
    H5语义化标签
  • 原文地址:https://www.cnblogs.com/del/p/1367016.html
Copyright © 2011-2022 走看看