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
}
}
精彩评论