[英]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类的实例。
您可以执行以下任一操作
使用前初始化
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.