繁体   English   中英

在C#中默认将值设置为EMPTY但不是NULL

[英]Setting values to EMPTY but not NULL by default in C#

我的代码中有一个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默认情况下有一个EMPTY而不是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>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM