zoukankan      html  css  js  c++  java
  • 子类构造

    1.通过子类无参构造函数创建子类实例

    创建父类Person和子类Student。

    复制代码
    public class Person
    {
        public Person()
        {
          Console.WriteLine("我是人");
        }
    }
    public class Student : Person
    {
        public Student()
        {
          Console.WriteLine("我是学生");
        }
    }
    复制代码

    2.在客户端通过子类无参构造函数创建子类实例。

    复制代码
    class Program
    {
        static void Main(string[] args)
        {
          Student student = new Student();
          Console.ReadKey();
        }
    }
     
    复制代码

    二、通过子类有参构造函数创建子类实例

    再同时为子类和父类添加有参构造函数。

    复制代码
    public class Person
    {
        public Person()
        {
          Console.WriteLine("我是人");
        }
        public Person(string name)
        {
          Console.WriteLine("我是人,我的名字叫{0}", name);
        }
    }
    public class Student : Person
    {
        public Student()
        {
          Console.WriteLine("我是学生");
        }
        public Student(string name)
        {
          Console.WriteLine("我是学生,我的名字叫{0}", name);
        }
    }
    复制代码

    三、在子类中明确指出调用哪个父类构造函数

    以上,默认调用了父类的无参构造函数,但如何调用父类的有参构造函数呢?
    --在子类中使用base

    在子类Student中的有参构造函数中使用base,明确调用父类有参构造函数。

    复制代码
    public class Student : Person
    {
        public Student()
        {
          Console.WriteLine("我是学生");
        }
        public Student(string name)
          : base(name)
        {
          Console.WriteLine("我是学生,我的名字叫{0}", name);
        }
    }
    复制代码

    四、通过子类设置父类的公共属性

    在父类Person中增加一个Name公共属性,并在父类的构造函数中对Name属性赋值。

    复制代码
    public class Person
    {
        public string Name { get; set; }
        public Person()
        {
          Console.WriteLine("我是人");
        }
        public Person(string name)
        {
          this.Name = name;
          Console.WriteLine("我是人,我的名字叫{0}", name);
        }
    }
  • 相关阅读:
    Python使用requirements.txt安装类库
    virtualenv -- python虚拟沙盒(linux版本)
    linux下导入、导出mysql数据库命令
    linux中mysql基本操作
    aspx.cs方法设置webmenthod特性接收ajax请求
    vue高级路由
    浅析JS模块规范:AMD,CMD,CommonJS
    当前不会命中断点还未为文档加载任何符号——问题探究
    Node.js安装及环境配置之Windows篇
    NewtonSoft.Json NULL转空字符串
  • 原文地址:https://www.cnblogs.com/zfx123--/p/6599681.html
Copyright © 2011-2022 走看看