结构中的公共字段是邪恶的,当你不注意时会在背后捅你一刀!
也就是说,您可以在 (parameterfull) 构造函数中对其进行初始化,如下所示:
public struct MyStruct
{
public decimal SomeDecimalValue;
public int SomeIntValue;
public List<string> SomeStringList;
public MyStruct(decimal myDecimal, int myInt)
{
SomeDecimalValue = myDecimal;
SomeIntValue = myInt;
SomeStringList = new List<string>();
}
public void Add(string value)
{
if (SomeStringList == null)
SomeStringList = new List<string>();
SomeStringList.Add(value);
}
}
请注意,SomeStringList如果有人使用默认构造函数,则仍然为 null:
MyStruct s = new MyStruct(1, 2);
s.SomeStringList.Add("first string");
s.Add("second string");
MyStruct s1 = new MyStruct(); //SomeStringList is null
//s1.SomeStringList.Add("first string"); //blows up
s1.Add("second string");