zoukankan      html  css  js  c++  java
  • c#基础学习(0806)之抽象类实现多态

    首先,要判断是否使用抽象类,可以从下面两个方面进行判断:

    1、是不是需要被实例化

    2、父类中有没有默认的实现

    如果不需要被实例化,父类中没有默认的实现,则用抽象类(否则用虚方法来实现)

    下面举个简单的例子:

    namespace 抽象类实现多态案例
    {
        class Program
        {
            static void Main(string[] args)
            {
                //Student s = new Student();
                Person p = new Student();
                p.SayHi();
                p.Standup();
            }
            //尽量用抽象来传输,不要用具体
            //static void M1(Person p)
            //{
            //    p.Standup();
            //}
            //static Person M2()
            //{
    
            //}
        }
        abstract class Person
        {
            public abstract void SayHi();
            public abstract void Standup();
        }
        class Student : Person
        {
            public override void SayHi()
            {
                throw new NotImplementedException();
            }
            public override void Standup()
            {
                throw new NotImplementedException();
            }
        }
        class Teacher : Person
        {
            public override void SayHi()
            {
                throw new NotImplementedException();
            }
            public override void Standup()
            {
                throw new NotImplementedException();
            }
        }
    }

     抽象类的另一个练习

    namespace 抽象练习
    {
        class Program1
        {
            static void Main(string[] args)
            {
                Duck duck = new RubberDuck();
                duck.Swim();
                duck.Bark();
                Console.ReadKey();
            }
        }
        public abstract class Duck
        {
            public void Swim()
            {
                Console.WriteLine("鸭子水上漂。。。");
            }
            public abstract void Bark();
        }
        public class RubberDuck: Duck
        {
            public override void Bark()
            {
                Console.WriteLine("橡皮鸭的叫声。。。");
            }
        }
        public class RealDuck : Duck
        {
            public override void Bark()
            {
                Console.WriteLine("真鸭的叫声。。。");
            }
        }
    }
  • 相关阅读:
    118/119. Pascal's Triangle/II
    160. Intersection of Two Linked Lists
    168. Excel Sheet Column Title
    167. Two Sum II
    172. Factorial Trailing Zeroes
    169. Majority Element
    189. Rotate Array
    202. Happy Number
    204. Count Primes
    MVC之Model元数据
  • 原文地址:https://www.cnblogs.com/chao202426/p/9430329.html
Copyright © 2011-2022 走看看