如何为一个与继承不同的类调用base()

时间:2016-07-26 20:53:47

标签: c# inheritance

我想我可能会让C ++与C#混淆但我不明白为什么在这个C#代码中他们会重新调用超类base()。一切都已经遗传了吗?

    class Animal
    {
      public double height{get;set;}

      public Animal()
      {
        this.height=0;
      }

    class Dog:Animal
    {
      public string favFood{get;set;}

      public Dog():base() //Why not just omit the base? Doesn't dog inherit already from Animal?
      {
        this.favFood="No favorite food";
      }
    }
   }

4 个答案:

答案 0 :(得分:0)

所有构造函数都必须调用其基类型的构造函数。只要C#允许您省略对base()的调用,只要基类型中有默认构造函数即可。但是,在编译代码时,默认情况下会调用基础构造函数。 (请记住,C#中的所有内容都是一个对象,因此技术上甚至Animal正在调用其基类型的构造函数,但如果没有明确的base()调用,它始终会调用{System.Object 1}}'的默认构造函数。

当基类型具有非默认构造函数时,base关键字开始派上用场,因为这允许您确定要调用的构造函数。

class Animal
{
  private readonly string name;
  public double height{get;set;}

  public Animal(string name)
  {
    this.name = 0;
    this.height=0;
  }

class Dog:Animal
{
  public string favFood{get;set;}

  public Dog():base("Fido")
  {
    this.favFood="No favorite food";
  }
}

}

在上面的示例中,name只能由Animal的构造函数设置,因此Dog必须通过{{base()向该构造函数发送值1}}关键字。

答案 1 :(得分:0)

考虑以下事项。在这种情况下,Animal有一个构造函数,其中一个参数类型为double。因为,Dog继承Animal应该将此参数提供给基础构造函数

class Animal
{
    public double Height { get; set;}

    public Animal(double height)
    {
        Height = height;
    }
}

class Dog: Animal
{
    public string FavoriteFood { get; set; }

    public Dog(double height): base(height) 
    {
        FavoriteFood = "No favorite food";
    }
}

在你的情况下,正如itsme86和Jon Skeet已经提到的那样,你不必使用: base(),因为你的基础构造函数是无参数的。

答案 2 :(得分:0)

您正在讨论的语句base()是指定要调用的基类的构造函数,这样如果您有两个不同的构造函数,您可以选择执行哪个:< / p>

class Animal
{
  public double Height{get;set;}
  public string Name {get; private set;}

  public Animal()
  {
    this.height=0;
  }

  protected Animal(string name)
  {
    Name=name;
  }
}

class Dog : Animal
{
   public string FavoriteFood{get;set;}

  //this calls the constructor with name parameter
  public Dog(string name):base(name)
  {
    this.FavoriteFood="No favorite food";
  }

  //this one calls the parameterless constructor
  //this is optional, if its not included then 
  //behaves the same as : base()
  protected Dog(int height):base()
  {
    this.favFood="No favorite food";
  }
}

这个语法也可以用来调用来自同一个类的其他构造函数,如果你有一个参数化的构造函数并且想要一个默认的参数集,那么这个构造函数很有用

//this construtor calls the current classes constructor taking a name 
protected Dog():this("Dog")
{

}

答案 3 :(得分:0)

它已经种类,但是除了能够将参数传递给基类型构造函数之外,这种机制还允许选择在基类型上调用哪些构造函数重载。