C#调用变坏了

时间:2011-10-13 09:17:50

标签: c# invoke

ListBox是一个列表框 ServerClient是具有arraylist

的类的实例
Arraylist pclist = new Arraylist();

temping是字符串数组

strings[] temping = new string[6];

现在,在执行期间...我得到的错误是: “附加信息:对象引用未设置为对象的实例。”

this.ListBox.Invoke(new MethodInvoker(delegate
{
    for (int i = 0; i < ServerClient.pclist.Count; i++)
    {
        // I am Alive,MyPcName,192.168.1.1,Status,NickName,datetime
        temp = ServerClient.pclist[i].ToString();
        temping = temp.Split(',');

        ListBox.Items.Add(temping[4] + "( " + temping[3] + " )");
    }

    for (int i = ServerClient.pclist.Count; i < ListBox.Items.Count; i++)
    {
        ListBox.Items.RemoveAt(i);
    }
}));

2 个答案:

答案 0 :(得分:1)

如果我是你,我会拆分我的Invoke函数,以便在其他地方声明被调用的委托函数。像这样的内联函数声明可能已经足够糟糕地进行调试,但代表是双倍的。

我认为你会发现,通过以这种方式声明你的内联函数,编译器将所有变量分配为本地变量,这些变量在使用前不会被初始化。

答案 1 :(得分:0)

当您在最后一个循环中删除具有RemoveAt的项目时,您必须向下而不是向上,因为每次使用RemoveAt删除项目时,最后一项的索引都会减少。如果你循环下来,这不会影响结果:

for (int i = ListBox.Items.Count - 1; i >= ServerClient.pclist.Count; i--)
{
    ListBox.Items.RemoveAt(i);
}