zoukankan      html  css  js  c++  java
  • 构造函数中base与this的区别

    base是对父类的引用,而this是对类本身的引用。

    namespace ConsoleApplication1
    {
        public class BaseClass
        {
            private string name;
            private int age;
            private string addr;
            public BaseClass()
            {
                Console.WriteLine("No Info");
            }
            public BaseClass(string name)
            {
                this.name = name;
                Console.WriteLine("name=" + this.name);
            }
            public BaseClass(string name, int age)
            {
                this.name = name;
                this.age = age;
                Console.WriteLine(string.Format("name={0},age={1}" ,this.name,this.age));
            }
    
            public BaseClass(string name, int age,string addr)
            {
                this.name = name;
                this.age = age;
                this.addr = addr;
                Console.WriteLine(string.Format("name={0},age={1},addr={2}", this.name, this.age, this.addr));
            }
        }
    
        public class ItemClass : BaseClass
        {
            private string name;
            private int age;
    
            public ItemClass()
                : this("demo")
            {
                //Console.WriteLine("No Info");
            }
            public ItemClass(string name)
                : this("jimmy", 20)
            {
                this.name = name;
                Console.WriteLine("name=" + this.name);
            }
            public ItemClass(string name, int age)
            {
                this.name = name;
                this.age = age;
                Console.WriteLine(string.Format("name={0},age={1}", this.name, this.age));
            }
            public ItemClass(string name,int age,string addr)
                : base("jeason", 20,"shanghai")
            {
                Console.WriteLine("name=" + name);
            }
    
            public static void Main()
            {
                ItemClass ic1 = new ItemClass("mike");
                ItemClass ic2 = new ItemClass();
                ItemClass ic3 = new ItemClass("mike",21,"chengdu");
            }
        }
    } 

    子类与基类的构造函数执行顺序:

    先调用父类的构造函数进行初始化,再调用继承类的构造函数,如果没有在继承类中指明父类的构造函数,则默认调用父类中无参构造函数,然后调用继承类的构造函数。 

  • 相关阅读:
    如何一次插入多条记录的SQL语句
    oracle 创建联合主键语句
    02-36 支持向量回归
    245 第三篇:Django-路由控制
    244 第二篇:Django简介
    243 第一篇:自定义Web框架
    242 第一篇:Http协议详细介绍
    02-34 非线性支持向量机(鸢尾花分类)+自定义数据分类
    241 第一篇:web应用
    240 vue学习【第6篇】:vue之导入Bootstrap
  • 原文地址:https://www.cnblogs.com/chenh/p/7895592.html
Copyright © 2011-2022 走看看