[英]Why does the call to a parent class constructor not call the parent's methods that are overriden in the child class?
[英]In .NET, does a parent class' constructor call its child class' constructor first thing?
public class Parent
{
Child child1;
public Parent()
{
child1.Name = "abc";
}
...
}
獲取一個NullReferenceException。 我以為Parent()構造函數首先調用Child()構造函數,以便以后可以在Parent()構造函數中訪問child1對象?
您需要創建子實例; 可以按照定義對其進行初始化:
Child child1 = new Child();
或在Parent構造函數中:
public Parent(){
child1 = new Child();
child1.Name = "Andrew";
}
父類的構造函數不會為其成員調用構造函數。 如果成員是引用,則將其設置為null。 您需要通過調用child1 = new Child
來顯式分配它
成員不是隱式構造的。 它們使用其默認值(即,引用類型成員為null
)初始化,這就是為什么child1
成員為null的原因。
您需要創建child1
的實例:
public Parent
{
child1 = new Child();
}
在旁注中,我認為您對繼承的類的構造函數調用規則感到困惑。 如果您的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.