簡體   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