質問

I have encounter the stated exception in my codes. Then I search online for this exception and have done what I can, creating an instance, making the elements to be added to an ObservableCollection. Probably the NullException comes from personID[0]? But for array, it always start from 0.. Like an array of 8 is from 0 to 7. I couldn't figure out why this exception persist. Could you please lend a helping hand to me? Your help will be much appreciated and thanks a lot in advance.

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++;
                }
            } 

As seen from the code, I wrote "PersonId[] personId = new PersonId[lineCount];" an instance in an array to solve the exception, but the problem still persist. If it's because y = 0, that means if I have an array of 120, then i can only have 119 elements filled? Thank you for your time.

役に立ちましたか?

解決

The problem is in the line

PersonId[] personId = new PersonId[lineCount];

PersonId is a class (reference type) so when you create the array, all the elements are initialized to null. You need to create an instance for each array element.

One way to do that would be to insert this line immediately before the line that throws the exception:

personId [y] = new PersonId();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top