一:基类和派生类中都无定义的构造函数,构造函数初始化顺序是private string name-〉public int age,在这里由于private string name无自定义的构造函数进行初始化,故其使用默认值为Null:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Demo
- {
- class Program
- {
- static void Main(string[] args)
- {
- Name name = new People();
- Console.WriteLine("Name is: "+name.ToString());
- Console.ReadLine();
- }
- }
- public class Name
- {
- private string name;
- public override string ToString()
- {
- return name;
- }
- }
- public class People : Name
- {
- public int age;
- public void Output()
- {
- Console.WriteLine(age);
- }
- }
- }
结果为空值:
二:基类和派生类中都有定义的无参数构造函数,构造函数初始化顺序是private string name-〉public int age,在这里由于private string name有自定义的无参数构造函数进行初始化,故其使用初始化值为“Hello”:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Demo
- {
- class Program
- {
- static void Main(string[] args)
- {
- Name name = new People();
- Console.WriteLine("Name is: "+name.ToString());
- Console.ReadLine();
- }
- }
- public abstract class Name
- {
- private string name;
- public Name()
- {
- this.name = "Hello";
- }
- public override string ToString()
- {
- return name;
- }
- }
- public class People : Name
- {
- public int age;
- public People()
- {
- this.age = 5;
- }
- public void Output()
- {
- Console.WriteLine(age);
- }
- }
- }
结果“Hello”:
三:基类和派生类中都有定义的有参数构造函数,构造函数初始化顺序是private string name-〉public int age,在这里由于People构造函数会试图调用Name的无参数构造函数,所以这里会产生一个编译错误:'Demo.Name' does not contain a constructor that takes 0 arguments。所以这里要为People添加一个构造函数。详情,见代码:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace Demo
- {
- class Program
- {
- static void Main(string[] args)
- {
- Name name = new People("Hello");
- Console.WriteLine(name.ToString());
- People people = new People("Hello");
- people.Output();
- Console.ReadLine();
- }
- }
- public abstract class Name
- {
- private string name;
- public Name(string name)
- {
- this.name = name;
- }
- public override string ToString()
- {
- return "Name is: "+name;
- }
- }
- public class People : Name
- {
- public int age;
- public People(string name)
- :base(name)
- {
- this.age=5;
- }
- public void Output()
- {
- Console.WriteLine("Age "+age);
- }
- }
- }
结果:
转载于:https://blog.51cto.com/2131406/1054189