美文网首页
C#学习笔记<三> 继承

C#学习笔记<三> 继承

作者: 七面琅琊 | 来源:发表于2017-12-18 21:15 被阅读0次

    m_<:这里记录C#学习的笔记,基础的语法略去,重点在类、方法、继承三项。

    1 类继承

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Chinese p1 = new Chinese();
                Japanese p2 = new Japanese();
                p1.Name = "ZhengLantern";
                p1.Age = 20;
                p1.Hometown = "WuHan";
                p1.Kongfu();
                p1.SayHello();
                p2.QRZ();
                Console.ReadKey();
            }
        }
    
        class Person
        {
            public string Name {get; set;}
            public int Age {get; set;}
            public void SayHello()
            {
                Console.WriteLine("{0}", this.Name);
            }
        }
        class Chinese : Person   //继承Person
        {
            public string Hometown { get; set; }
            public void Kongfu()
            {
                Console.WriteLine("KO!");
            }
        }
        class Japanese : Person   //继承Person
        {
            public void QRZ()
            {
                Console.WriteLine("Stay at home.");
            }
        }
    }
    

    2

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                Chinese p1 = new Chinese();
                Person p2 = p1;   //定义一个Person,并指向Chinese
                //Chinese p3 = p2;   类型错误
                Chinese p3 = (Chinese)p2;   //强制类型转换
                p1.Name = "ZhengLantern";
                p1.Age = 20;
                p1.Kongfu();
                p2.SayHello();
                Console.ReadKey();
                object ob = p1;   //object是所有类的基类
            }
        }
    
        class Person
        {
            public string Name {get; set;}
            public int Age {get; set;}
            public void SayHello()
            {
                Console.WriteLine("{0}", this.Name);
            }
        }
        class Chinese : Person
        {
            public string Hometown { get; set; }
            public void Kongfu()
            {
                Console.WriteLine("KO!");
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:C#学习笔记<三> 继承

          本文链接:https://www.haomeiwen.com/subject/mjzzixtx.html