在C#中,默认情况下将值设置为EMPTY,但不为NULL
本文关键字:NULL EMPTY 设置 默认 情况下 | 更新日期: 2023-09-27 18:20:29
我的代码中有一个Mainclass
,包含各种列表和子集。当我尝试时
main k = new main();
k.main.addressinfo.addressline1 = "XXX";
我得到错误"对象引用未设置为对象的实例//NULLEXCEPTION。"
public class Mainclass
{
public List<main> mainset { get; set; }
// do sth to load and save model info
}
public class main
{
public personalinfo info { get; set; }
public addressinfo currentaddr { get; set; }
public addressinfo[] otheraddr { get; set; }
public telephone currenttel { get; set; }
public telephone[] othertel { get; set; }
}
public class addressinfo
{
public string Addressline1 { get; set; }
public string Addressline2 { get; set; }
public string City { get; set; }
public string postcode { get; set;
}
public class telephone
{
public int tel { get; set; }
}
由于Class包含列表和数组,我有点困惑如何将字符串的默认值设置为EMPTY而不是NULL。此外,我如何确保Childrens默认情况下有一个空对象而不是NULL对象?
您需要初始化对象
public personalinfo info = new personalinfo();
public addressinfo currentaddr = new addressinfo();
public telephone currenttel = new telephone();
您必须为类定义构造函数,并在其中将属性设置为默认值。
@Using mcmonkey4eva
应答
public personalinfo info = new personalinfo();
public addressinfo currentaddr = new addressinfo();
public telephone currenttel = new telephone();
public addressinfo[] otheraddr = new addressinfo[1];
public List<main> mainset = new List<main>();