C#简单封装的理解

以人说语言为例:
接口:

interface IPeople
    {
        public void SayHello();
    }
    class Chinese : IPeople
    {
        public void SayHello()
        {
            Console.WriteLine("你好");
        }
        public void KongFu()                      //多态,因为American类中没有
        {
            Console.WriteLine("太极,咏春");
        }
    }
    class American : IPeople
    {
        public void SayHello()
        {
            Console.WriteLine("hello");
        }
         public void Fight()
        {
            Console.WriteLine("taekwondo ");
        }
    }
     class Program
    {
        public static void Say(IPeople people)   //无类别进行调用,好处就是只知道基类即可
        {
            people.SayHello();
        }
        static void Main(string[] args)
        {
            IPeople people1;
            IPeople people2;
            people1 = new Chinese();            //通俗我的理解是:1.子类可以赋值给父类,而父类不可以赋值给子类
            Say(people1);                       //你好
                                                //2.父类有的属性,子类必然有,而子类有的属性父类未必有,而子类间的属性未必完全相同(多态)
            people2 = new American();           //3.子类赋值给父类(里氏代换),父类自然可以安全调用自身方法,加入倒过来(不可以),则会出现空指针(内存泄漏)(个人简便理解)
            Say(people2);                       //hello
        }
     }

抽象类:

 abstract class People
    {
        public abstract void SayHello();
    }
    class Chinese : People
    {
        public override void SayHello()
        {
            Console.WriteLine("你好");
        }
        public void KongFu()                      //多态,因为American类中没有
        {
            Console.WriteLine("太极,咏春");
        }
    }
    class American : People
    {
        public override void SayHello()
        {
            Console.WriteLine("hello");
        }
         public void Fight()
        {
            Console.WriteLine("taekwondo ");
        }
    }
   class Program
    {
        public static void Say(People people)   //无类别进行调用,好处就是只知道基类即可
        {
            people.SayHello();
        }
        static void Main(string[] args)
        {
            People people1;
            People people2;
            people1 = new Chinese();            //通俗我的理解是:1.子类可以赋值给父类,而父类不可以赋值给子类
            Say(people1);                       //你好
                                                //2.父类有的属性,子类必然有,而子类有的属性父类未必有,而子类间的属性未必完全相同(多态)
            people2 = new American();           //3.子类赋值给父类(里氏代换),父类自然可以安全调用自身方法,加入倒过来(不可以),则会出现空指针(内存泄漏)
            Say(people2);                       //hello
        }
     }

你可能感兴趣的:(C#)