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);
        }
    }
  • 相关阅读:
    C/S 随思录
    3dTiles 最后一块拼图:几何误差与屏幕空间误差
    aps.net cannot connect to runtime process
    asp.net web api swagger使用总结
    asp.net webaip 跨域
    LightGBM算法实践
    Zabbix 机器 CPU 飙高 和 时区相差8个小时
    【vue踩坑记录】3、“Error in render: "TypeError: Cannot read property '0' of undefined"”渲染错误问题
    1-关于补码的理解
    vscode快捷键
  • 原文地址:https://www.cnblogs.com/zfx123--/p/6599681.html
Copyright © 2011-2022 走看看