简体   繁体   English

初始化数组后无法将对象添加到数组

[英]Can't add objects to an array after initializing the array

I'm trying to initialize an array of objects with predetermined values but I get "Object reference not set to an instance of an object". 我正在尝试使用预定值初始化对象数组,但得到“对象引用未设置为对象实例”。
I don't understand the cause of the problem since I'm initializing properly and then I'm adding values to the array. 我不了解问题的原因,因为我已正确初始化,然后将值添加到数组中。
The main is: 主要是:

Sorteo P=new Sorteo();
P.Predetermined();

Class Sorteo: 类Sorteo:

// Atribute
private ClassA[] A;
int count=0;

// Methods
public Sorteo()
{
    A=new ClassA[2];
}
public void Add(ClassA a)
{
    A[count]=a;
    count++;
}
public void PredeterminedValues()
{
    A[0].Add(new ClassB("SomeString1"));
    A[1].Add(new ClassB("SomeString2"));
}

You're dealing with an array of reference types, not a value type. 您正在处理的是引用类型数组,而不是值类型。

In the following line: 在以下行中:

    A = new ClassA[2]; 
    //[0] -> null
    //[1] -> null

you have indeed initialized an array which holds reference objects of type ClassA . 您确实已经初始化了一个数组,其中保存了ClassA类型的引用对象。

In this case it actually holds two variables of type ClassA, but each of them is going to be set to null (since you have't initialized those), and therefore when you try to reference them the exception Object reference not set to an instance of an object is going to be thrown. 在这种情况下,它实际上拥有两个ClassA类型的变量,但是每个变量都将被设置为null(因为尚未初始化它们),因此,当您尝试引用它们时, 没有将Object引用设置为实例物体将被抛出。

Solution? 解?

Add this after initializing your array 初始化数组后添加

A[0] = new ClassA(); // not null anymore
A[1] = new ClassA(); // not null anymore

I'm struggling to understand your question but is this what you were trying to do? 我正在努力理解您的问题,但这是您想要做的吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace YourNameSpace
{
    public class Program
    {
        public static void Main(string[] args)
        {
            ClassA Item = new ClassA();
            Item.PredeterminedValues();

            foreach(string s in Item.StringArray)
            {
                Console.WriteLine(s);
            }
        }
    }

    public class ClassA
    {
        public int Counter {get;private set;}
        public string[] StringArray{get;private set;}

        public ClassA()
        {
            StringArray = new string[2];
        }

        public void Add(int Value)
        {
            Counter += Value;   
        }

        public void PredeterminedValues()
        {
            StringArray[0] = ("SomeString1");
            StringArray[1] = ("SomeString2");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM