Skip to main content
 首页 » 编程设计

c#之为什么不能创建抽象类实例但可以调用其构造函数

2024年02月06日20zhujiabin

我知道我们不能创建抽象类实例,但我不明白为什么可以使用base调用抽象类的构造函数。

abstract class Fruit 
{ 
    public string Name { get; private set; } 
 
    public Fruit(string name) 
    { 
        Name = name; 
    } 
} 
 
class Apple : Fruit 
{ 
    public Apple(string name) : base(name) { } 
} 
 
 
Fruit f = new Fruit("Fruit");  // Coimple Error 
Apple a = new Apple("Apple");  // Success 
  • 难道 base 关键字只是调用构造函数、方法等吗?

  • 创建实例和调用构造函数有什么区别?

提前致谢。

请您参考如下方法:

只有派生类(例如 Apple)可以使用特殊的 base 字调用其父类(抽象类)的构造函数。不能直接调用(调用)构造函数。