使用base的情况:
static void Main(string[] args)
{
//本文来自 www.LuoFenMing.com
Animal animal = new Dog("Dog");
animal.SayName();//输出结果: My Name is Dog
Console.ReadKey();
}
public abstract class Animal
{
public Animal(string name)
{
this.AName = name;
}
public string AName { get; set; }
public abstract void SayName();
}
public class Dog : Animal
{
//继承 Animal必须也要有一个带 一个string类型的构造函数
public Dog(string dName) : base(dName)
{
}
public override void SayName()
{
Console.WriteLine("My Name is " + this.AName);
}
}
在 C# 里,当一个派生类(如 Dog
类)继承自一个基类(如 Animal
类),并且基类定义了一个带参数的构造函数(非默认构造函数)时,派生类的构造函数必须显式调用基类的某个构造函数。这是因为基类的成员变量需要通过其构造函数来进行初始化,派生类对象的创建依赖于基类对象的正确初始化。
在你的代码中,Animal
类定义了一个带 string
类型参数的构造函数:
public Animal(string name)
{
this.AName = name;
}
因此,Dog
类的构造函数就必须显式调用 Animal
类的这个构造函数,而使用 base
关键字就是显式调用基类构造函数的方式。
不使用 base
的后果
如果你不使用 base
关键字,编译器会报错。以下是一个不使用 base
的错误示例:
using System;
// 抽象基类 Animal
public abstract class Animal
{
public Animal(string name)
{
this.AName = name;
}
public string AName { get; set; }
public abstract void SayName();
}
// 派生类 Dog
public class Dog : Animal
{
public Dog(string dName)
{
// 没有使用 base 调用基类构造函数
}
public override void SayName()
{
Console.WriteLine($"My Name is {this.AName}");
}
}
class Program
{
static void Main()
{
Dog dog = new Dog("Buddy");
dog.SayName();
}
}
当你尝试编译这段代码时,编译器会给出类似下面的错误信息:
'Animal' does not contain a parameterless constructor.
这个错误提示表明 Animal
类没有无参构造函数,而 Dog
类的构造函数没有显式调用 Animal
类的带参构造函数,编译器无法自动找到合适的基类构造函数来调用。
特殊情况:基类有默认构造函数
如果基类有默认构造函数(即无参构造函数),那么派生类的构造函数可以不使用 base
关键字显式调用基类构造函数,因为编译器会自动调用基类的默认构造函数。示例如下:
using System;
// 基类 Animal
public class Animal
{
public Animal()
{
Console.WriteLine("Animal default constructor is called.");
}
public string AName { get; set; }
public void SayName()
{
Console.WriteLine($"My Name is {this.AName}");
}
}
// 派生类 Dog
public class Dog : Animal
{
public Dog()
{
Console.WriteLine("Dog constructor is called.");
}
}
class Program
{
static void Main()
{
Dog dog = new Dog();
}
}
在这个例子中,Animal
类有一个默认构造函数,Dog
类的构造函数没有使用 base
关键字,编译器会自动调用 Animal
类的默认构造函数。
综上所述,在你的代码里由于 Animal
类只有带参构造函数,所以 Dog
类的构造函数必须使用 base
关键字来调用基类的构造函数。