在C#中创建struct的arraylist

时间:2010-07-01 21:11:47

标签: c# struct arraylist

我有一个结构

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

但是,我收到错误“对象引用未设置为对象的实例。”

任何人都可以告诉我为什么?

感谢。

6 个答案:

答案 0 :(得分:6)

由于你声明字典a没有实例化它,你试图将一个项添加到null。这假设您将它们标记为公开,否则无法编译。

答案 1 :(得分:5)

改善代码的一些建议:

  • 请勿使用struct,而是使用class。 .NET中的结构是a little different,除非我们理解这些差异,否则我怀疑结构的有效用途。 class几乎总是你想要的。

  • ArrayListmore or less obsolete,使用通用List<T>几乎总是更好。即使您需要在列表中放置混合对象,List<object>也是比ArrayList更好的选择。

  • 在访问其成员的方法或属性之前,请确保您的成员已正确初始化,而不是null

  • 最好是use properties而不是公共字段。

以下是一个例子:

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);
...

答案 2 :(得分:4)

问题是ab都未启动。将它们分别设置为新的字典。

根据评论编辑:

然后您的问题在其他地方,因为以下工作正常:

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

答案 3 :(得分:2)

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

这可以解决您的问题。您需要做的是通过属性(getter)访问字典。

答案 4 :(得分:1)

mystruct s已初始化,不会为您提供空引用异常。初始化时,它会将其成员设置为默认值。因此,它将ab成员设置为null,因为它们是引用类型。

答案 5 :(得分:1)

这可能是问题所在:

“使用 new 运算符创建结构对象时,会创建它并调用相应的构造函数。与类不同,可以在不使用new运算符的情况下实例化结构。如果不使用new,这些字段将保持未分配状态,并且在初始化所有字段之前无法使用该对象。“

也许你还没有新建你的结构,或者隐藏在...后面的一些字段尚未初始化?

http://msdn.microsoft.com/en-us/library/ah19swz4(VS.71).aspx