【问题标题】:(C#) How do you deal with a Base class with a constructor, when you want to make an inheriting class?(C#) 当你想创建一个继承类时,你如何处理带有构造函数的基类?
【发布时间】:2019-11-23 20:38:17
【问题描述】:

我正在尝试创建一个 Dog 类,继承具有构造函数的 Animal 基类。有什么办法可以让类 Dog : Animal,但以某种方式使用 Animal 构造函数?我查看了类似的问题,但没有得到我正在寻找的答案。

class Class1
{       
   static void Main(string[] args)
   {
        Animal animal = new Animal("Spotty", 5, 4);
        animal.Print();
   }
}

class Animal
{
    public string animalName;
    public int animalAge;
    public int animalLegs;
    public Animal(string name, int age, int legs)
    {
        animalName = name;
        animalAge = age;
        animalLegs = legs;       
    }       

    public void Print()
    {
        Console.WriteLine("Name: " +animalName);
        Console.WriteLine("Age: "+ animalAge);
        Console.WriteLine("Number of Legs: " +animalLegs);
    }
}

class Dog : Animal
{
    //This wont work; there will be an error
}

【问题讨论】:

  • Using Constructors (C# Programming Guide): 构造函数可以使用base关键字来调用基类的构造函数。
  • Animal.animalLegs 等等是相当多余的(tautology)。我希望动物除了动物腿之外没有其他种类的腿。从您周围的 NET 框架中获取提示,它是 Rectangle.Width 而不是 Rectangle.RectangleWidth。那个外壳也一样

标签: c# inheritance constructor base-class


【解决方案1】:

您应该将默认构造函数添加到Animal,或者将必要的构造函数添加到Dog

public Dog(string name, int age) : base(name, age, 4)
{
}

【讨论】:

  • 我不想吹毛求疵,但是……为什么 Dog ctor 有“腿”参数?我不知道你是否理解我...
猜你喜欢
  • 1970-01-01
  • 2016-05-22
  • 1970-01-01
  • 1970-01-01
  • 2014-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
相关资源
最近更新 更多