簡體   English   中英

創建新的父類屬性后出現NullReferenceException

[英]NullReferenceException after creating new parent class property

我想這是C#中的一個基本問題。 不過,我對此有些疑惑,但是我不確定如何對它進行排序。

我有一個具有get / set屬性的父類和一個子類。 使用new創建類的實例時,可以訪問父類的屬性,但不能訪問子類。 我記得在C編程中必須為此創建內存空間,但是我不確定在C#中執行此操作的正確方法。

家長班

class Parent_class
{
    private int number;
    public int Number
    {
        get { return number; }
        set { number = value; }
    }
    private Child_class childclass;// = new Child_class();
    public Child_class Childclass
    {
        get { return childclass; }
        set { childclass = value; }
    }
}

兒童班

class Child_class
{
    private int number;
    public int Number
    {
        get { return number; }
        set { number = value; }
    }
}

主要

    static void Main(string[] args)
    {
        Parent_class test = new Parent_class();
        test.Number = 3;            //<--Ok
        test.Childclass.Number = 4; //<--NullReferenceException
    }

如果您沒有做任何特別的事情,則不需要使用字段支持的getter / setter方法-編譯器可以為您創建它。

要獲取類的實例,您需要使用new 由於看起來您希望Parent_class自動具有子類的實例,因此可以在constructor執行此操作。

哦-Number正常工作的原因是primitive類型,而不是類。 基本體(int,float,bool,double,DateTime,TimeSpan等)不需要通過new實例化。

家長班

public class Parent_class
{
    public Parent_class()
    {
      Childclass = new Child_class();
    }
    public int Number { get; set; }
    public Child_class Childclass { get; set; }
}

兒童班

public class Child_class
{
    public int Number { get; set; }
}

主要

static void Main(string[] args)
{
    Parent_class test = new Parent_class();
    test.Number = 3;            //<--Ok
    test.Childclass.Number = 4;
}

您尚未創建Child類的實例。

您可以執行以下任一操作

  1. 使用前初始化

     static void Main(string[] args) { Parent_class test = new Parent_class(); test.Number = 3; //<--Ok test.ChildClass = new Child_class(); test.Childclass.Number = 4; //<--NullReferenceException } 

    2。 在父級ctor中初始化

      public Parent_class() { Childclass = new Child_class(); } 

3。 在聲明時初始化內聯

   private Child_class childclass = new Child_class();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM