简体   繁体   English

C#的子类中父类的构造方法

[英]parent class's constructer in a child class in C#

I have one parent class and one child class. 我有一个父母班和一个孩子班。 The parent has a constructor that initializes its parameters. 父级具有用于初始化其参数的构造函数。

My question is: How does the child look to the parent's constructor? 我的问题是:孩子如何看待父母的构造函数? Can I define a constructor for the children? 我可以为孩子定义一个构造函数吗?

This inheritance sample shows: 此继承示例显示:

  • how to call the parent constructor from a new constructor on the child 如何从子级上的新构造函数调用父级构造函数
  • how to pass parameters required by the parent constructor 如何传递父构造函数所需的参数

Code sample: 代码示例:

public class Parent
{
    private object _member;

    public Parent(object member)
    {
        this._member = member;
    }
}

public class Child : Parent
{
    public Child(object member)
        : base(member)
    {
    }
}

you can use base(...) in ctor of your child class. 您可以在类的ctor中使用base(...)

foreacmple: 前额:

public class Child : BaseClass 
{
    public Child() : base(/*some parameters*/) //CALLING BaseClass parametrized ctor
    {  
    }
}

Just note, if you don't need some specific parameters, just do not do anything , cause BaseClass default ctor will be called by the way when you call ctor of a Child class. 只要注意,如果你并不需要一些具体的参数,只是没有做任何事情 ,引起BaseClass默认ctor 将由方式调用,当你调用ctor一的Child类。

You have to define constructors for the children. 您必须为子代定义构造函数。 You can call the base class' constructor using : base() between the constructor prototype and its implementation: 您可以在构造函数原型及其实现之间使用: base()来调用基类的构造函数:

public class Parent {
  public Parent() {
    ...
  }
}

public class Child : Parent {
  public Child() : base() { // calls Parent.ctor
  }
}

Of course. 当然。

You are after the "base" keyword. 您在“ base”关键字之后。

public class Fruit
{
    string TypeOfFruit { get; set; }

    public Fruit (string typeOfFruit)
    {
        TypeOfFruit = typeOfFruit;
    }

}

public class Apple : Fruit
{
    string AppleType { get; set; }

    public Apple(string appleType) : base("Apple")
    {
        AppleType = appleType;
    }

}

You can very well define a constructor for the child class the default one is provided only in case when you do not define a constructor for a class 您可以很好地为子类定义一个构造函数,只有在不为一个类定义构造函数的情况下才提供默认的构造函数

Meanwhile for how to look up for the constructor of parent 同时关于如何查找parent的构造函数

It would check for a parameterless constructor to be present in the parent class and in case you do not have one ( well the compiler lets you know the same) or else you will have to call the parent constructor with the parameters like base("This is the string parameter") 它将检查无参数的构造函数是否存在于父类中,并且如果您没有该参数(编译器会让您知道相同的信息),否则您将不得不使用诸如base("This is the string parameter")

If you meant something else please update the question. 如果您还有其他意思,请更新问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM