2013-06-29 53 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 *符号标记为答案: –