在C#中创建struct的arraylist

Mav*_*ang 1 c# struct arraylist

我有一个结构

struct myStruct {
    Dictionary<string, int> a;
    Dictionary<string, string> b;
    ......
}
Run Code Online (Sandbox Code Playgroud)

我想创建该结构的arraylist

ArrayList l = new ArrayList();
myStruct s;

s.a.Add("id",1);
s.b.Add("name","Tim");

l.Add(s);
Run Code Online (Sandbox Code Playgroud)

但是,我收到错误"对象引用未设置为对象的实例".

谁能告诉我为什么?

谢谢.

Yur*_*ich 6

由于您对字典a的声明未实例化,因此您尝试将项添加到null.这假设您将它们标记为公开,否则无法编译.


Dir*_*mar 5

一些改善代码的建议:

  • 请勿使用struct,而应使用class。.NET中结构略有不同,除非有人了解这些差异,否则我怀疑有人会有效使用结构。A class几乎总是您想要的。

  • ArrayList或多或少过时,它几乎总是最好使用一个通用的List<T>来代替。即使您需要在列表中放置混合对象,List<object>也是比更好的选择ArrayList

  • 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);
...
Run Code Online (Sandbox Code Playgroud)