如何在处理数组和ObservableCollection时解决NullReferenceException?

时间:2014-05-15 13:17:20

标签: c# arrays observablecollection nullreferenceexception

我的代码中遇到了声明的异常。然后我在网上搜索这个异常并尽我所能,创建一个实例,使元素被添加到ObservableCollection中。 NullException可能来自personID [0]?但是对于数组,它始终从0开始。就像8的数组从0到7.我无法弄清楚为什么这个异常持续存在。你能帮帮我吗?非常感谢您的帮助,并提前感谢。

using (StreamReader file = new StreamReader(fileName))
            {
                if (this.PersonIdDetails == null)
                    PersonIdDetails= new ObservableCollection<PersonId>();
                else
                    this.PersonIdDetails.Clear();

                var lineCount = File.ReadLines(fileName).Count();

                PersonId[] personId = new PersonId[lineCount];

                int y = 0;

                while (file.Peek() >= 0)
                {
                    string line = file.ReadLine();
                    if (string.IsNullOrEmpty(line)) continue;
                    //To remove the whitespace of the to-be-splitted-elements
                    line = line.Replace(" ", "_");

                    char[] charSeparators = new char[] { '§', '�' };
                    string[] parts = line.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);

                    personId [y].QualName = parts[1]; //the exception is throw here. "Object reference not set to an instance of an object".
                    personId [y].ID = parts[2];
                    personId [y].Use.UserUse = true;
                    GetWriteablePropertyUser(personId [y], Convert.ToInt32(parts[3]));
                    GetReadablePropertyUser(personId [y], Convert.ToInt32(parts[3]));

                    PersonIdDetails .Add(personId [y]);

                    y++;
                }
            } 

从代码中可以看出,我写了“PersonId [] personId = new PersonId [lineCount];”数组中的一个实例来解决异常,但问题仍然存在。如果是因为y = 0,这意味着如果我有一个120的数组,那么我只能填充119个元素?谢谢你的时间。

1 个答案:

答案 0 :(得分:2)

问题出在

PersonId[] personId = new PersonId[lineCount];

PersonId是一个类(引用类型),因此在创建数组时,所有元素都被初始化为null。您需要为每个数组元素创建一个实例。

这样做的一种方法是在抛出异常的行之前插入这一行:

personId [y] = new PersonId();
相关问题