开发者

In .NET, does a parent class' constructor call its child class' constructor first thing?

开发者 https://www.devze.com 2023-01-19 14:34 出处:网络
public cla开发者_开发百科ss Parent { Child child1; public Parent() { child1.Name = \"abc\"; } ... } Gets a NullReferenceException. I thought the Parent() constructor calls the Child() constructor f
public cla开发者_开发百科ss Parent
{
    Child child1;

    public Parent()
    {
        child1.Name = "abc";
    }
    ...
}

Gets a NullReferenceException. I thought the Parent() constructor calls the Child() constructor first, so that it is possible to access child1 object later in the Parent() constructor???


You need to create an instance of the child; either initialize it as you define it:

Child child1 = new Child();

Or in the Parent constructor:

public Parent(){
    child1 = new Child();
    child1.Name = "Andrew";
}


The parent class's constructor doesn't call constructors for its members. When the member is a reference, it's just set to null. You need to explicitly allocate it by calling child1 = new Child


Members are not implicitly constructed. They're initialized with their default values (i.e. null for reference type members), which is why your child1 member is null.

You need to create an instance of child1:

public Parent
{
  child1 = new Child();
}

On a sidenote, I think you are being confused by constructor call rules for inherited classes. If your Child class inherited your Parent class, the Parent class' default (i.e. parameterless) constructor would be implicitly called (if it existed):

class Parent
{
  protected string member;
  public Parent()
  {
    member = "foo";
  }
}

class Child : Parent
{
  public Child()
  {
    // member is foo here; Parent() is implicitly called
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消