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);
        }
    }
  • 相关阅读:
    7-2 一元多项式的乘法与加法运算 (20 分)
    cvc-complex-type.2.4.a: Invalid content was found starting with element(servlet)
    MOOC 2.3 队列
    MOOC 2.2 堆栈
    MOOC 2.1 线性表及其实现
    MOOC 1.3 最大子列和
    计时程序
    MOOC 1.1 什么是数据结构
    poj3253
    二分法查找——对数
  • 原文地址:https://www.cnblogs.com/zfx123--/p/6599681.html
Copyright © 2011-2022 走看看