[英]In .NET, does a parent class' constructor call its child class' constructor first thing?
public class Parent
{
Child child1;
public Parent()
{
child1.Name = "abc";
}
...
}
Gets a NullReferenceException. 获取一个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???
我以为Parent()构造函数首先调用Child()构造函数,以便以后可以在Parent()构造函数中访问child1对象?
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: 或在Parent构造函数中:
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.
如果成员是引用,则将其设置为null。 You need to explicitly allocate it by calling
child1 = new Child
您需要通过调用
child1 = new Child
来显式分配它
Members are not implicitly constructed. 成员不是隐式构造的。 They're initialized with their default values (ie
null
for reference type members), which is why your child1
member is null. 它们使用其默认值(即,引用类型成员为
null
)初始化,这就是为什么child1
成员为null的原因。
You need to create an instance of child1
: 您需要创建
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 (ie parameterless) constructor would be implicitly called (if it existed): 如果您的
Child
类继承了您的Parent
类,则将隐式调用Parent
类的默认(即无参数)构造函数(如果存在):
class Parent
{
protected string member;
public Parent()
{
member = "foo";
}
}
class Child : Parent
{
public Child()
{
// member is foo here; Parent() is implicitly called
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.