[英]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.