[英]Create an arraylist of struct in C#
我有一個結構
struct myStruct {
Dictionary<string, int> a;
Dictionary<string, string> b;
......
}
我想創建該結構的arraylist
ArrayList l = new ArrayList();
myStruct s;
s.a.Add("id",1);
s.b.Add("name","Tim");
l.Add(s);
但是,出現錯誤“對象引用未設置為對象的實例”。
誰能告訴我為什么?
謝謝。
由於字典的聲明a不會實例化它,因此您試圖將一個項目添加到null中。 這是假設您將其標記為公開,否則將無法編譯。
一些改善代碼的建議:
不要使用struct
,而要使用class
。 .NET中的結構略有不同 ,除非有人了解這些差異 ,否則我懷疑有人會有效使用結構。 class
幾乎總是您想要的。
ArrayList
或多或少已經過時了 ,最好改用通用的List<T>
。 即使您需要在列表中放置混合對象,與ArrayList
相比, List<object>
是更好的選擇。
在訪問成員的方法或屬性之前,請確保成員已正確初始化且不為null
。
最好使用屬性而不是公共字段。
這是一個例子:
class Container
{
Dictionary<string, int> A { get; set; }
Dictionary<string, string> B { get; set; }
public Container()
{
// initialize the dictionaries so they are not null
// this can also be done at another place
// do it wherever it makes sense
this.A = new Dictionary<string, int>();
this.B = new Dictionary<string, string>();
}
}
...
List<Container> l = new List<Container>();
Container c = new Container();
c.A.Add("id", 1);
c.B.Add("name", "Tim");
l.Add(c);
...
問題在於a
和b
都不會啟動。 將它們分別設置為新字典。
按評論編輯:
然后您的問題就在其他地方,因為以下工作正常:
struct myStruct
{
public IDictionary<string, int> a;
public IDictionary<string, string> b;
}
IList<myStruct> l = new List<myStruct>();
myStruct s;
s.a = new Dictionary<string, int>();
s.b = new Dictionary<string, string>();
s.a.Add("id", 1);
s.b.Add("name","Tim");
l.Add(s);
struct myStruct {
private Dictionary<string, int> a;
private Dictionary<string, string> b;
public Dictionary<string, int> A
{
get { return a ?? (a = new Dictionary<string, int>()); }
}
public Dictionary<string, string> B
{
get { return b ?? (b = new Dictionary<string, string>()); }
}
}
這樣可以解決您的問題。 您需要做的是通過屬性(獲取器)訪問字典。
mystruct s
已初始化,不會為您提供null引用異常。 初始化時,將其成員設置為其默認值。 因此,將a
和b
成員設置為null
因為它們是引用類型。
這可能是問題所在:
“當使用new運算符創建結構對象時,將創建它並調用適當的構造函數。與類不同,可以在不使用new運算符的情況下實例化結構。如果不使用new,則字段將保持未分配狀態,並且該對象在所有字段都初始化之前不能使用。”
也許您尚未更新結構,或者隱藏在...
之后的某些字段尚未初始化?
http://msdn.microsoft.com/zh-CN/library/ah19swz4(VS.71).aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.