2013-06-29 45 views
1

我在我的代碼中有一個Mainclass,具有各種列表和各種子集。當我嘗試將值設置爲EMPTY,但在C#中默認不爲NULL

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; } 
} 

由於類包含列表和數組,我對如何設置字符串的默認值空,但不是NULL有點糊塗了。另外我如何確保Childrens默認情況下有一個EMPTY而不是NULL對象?

回答

3

需要初始化你的對象

public personalinfo info = new personalinfo(); 
public addressinfo currentaddr = new addressinfo(); 
public telephone currenttel = new telephone(); 
+0

我知道但什麼陣列?我是否也需要初始化它們? –

+1

是的,這會有所幫助。像這樣:'public addressinfo [] otheraddr = new addressinfo [2] {new addressinfo(),new addressinfo()};''所有'class'都需要初始化,'struct's不需要。 (EG,int和string都是'struct's) – mcmonkey4eva

+0

非常感謝:) –

0

你必須定義爲constructors類和它們內部設置屬性爲默認值。

0

@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>(); 
+0

如果mcmonkey4eva的答案是最能幫助你的答案,那麼你應該接受答案。 – Tim

+0

Tim說什麼 - 另外,public addressinfo [] otheraddr = new addressinfo [1];'應該可能是'public addressinfo [] otheraddr = new addressinfo [1] {new addressinfo(); };否則它將是一個只包含null的數組。 – mcmonkey4eva

+0

Didnt沒有意識到* Correct *符號標記爲答案: –

相關問題