1

我有一个类创建另一个类的列表。看起来像:

class SortItAll
{                                       
    Recipient rec;
    public List<Recipient> listofRec = new List<Recipient>();

    public void sortToClass()
    {
        while (isThereNextLine()) { //while there is a following line
            loadNextLine();         //load it

            rec = new Recipient(loadNextPiece(),  //break that line to pieces and send them as arguments to create an instance of "Recipient" class
                                loadNextPiece(),
                                loadNextPiece(),
                                loadNextPiece());
            listofRec.Add(rec);                   //add the created instance to my list
        }
    }

从我的 Form1 类中,我调用了这个方法 (sortToClass()),按照我的逻辑,它应该用那个特定的类填充我的列表。然后我想将 list.count() 写入文本框:

    public Form1()
    {
        SortItAll sort = new SortItAll(); //create the instance of the class

        sort.sortToClass();               //within which i call the method to fill my list

        txt_out.Text = sort.listofRec.Count().ToString(); //writing out its count to a textbox

        InitializeComponent();
    } 

现在我的问题是每当我尝试调试时,它都会阻止我

Nullreference exception pointing to -> "txt_out.Text = sort.listofRec.Count().ToString();" in Form1.

然而,在调试时,我可以检查当地人,它指出:

sort -> listOfRec -> Count = 4.

可能是什么问题?

4

2 回答 2

3

 txt_out.Text = sort.listofRec.Count().ToString(); //writing out its count to a textbox

在 InitializeComponent() 之后,因为它是在该方法中创建的。

于 2013-04-22T18:46:07.697 回答
0

You should keep InitializeComponent(); at the top of the method as it creates all the controls on the form. You are probably getting it because you are trying to access control txt_out before it has been created and added to the form.

于 2013-04-22T18:49:23.793 回答