在事件委托上使用 - =时,System.ArgumentException未处理?

时间:2010-02-14 19:29:32

标签: c# exception delegates

我有这段代码:

public void setPanelHalfHorizontalScreen(Panel p)
        {
            if (p != null)
            {
                p.Width = Screen.PrimaryScreen.Bounds.Width / 2 - 2;
                this.panelsForHalfScreen.Add(p.Name, p);

                // http://stackoverflow.com/questions/2261828/does-an-event-gets-executed-twice-if-callback-was-assigned-twice-to-the-object
                this.form.Resize -= new EventHandler(form_Resize); // error raised on this line: ArgumentException was unhandled
                this.form.Resize += new EventHandler(form_Resize);
            }
        }

        void form_Resize(object sender, EventArgs e)
        {

            foreach (DictionaryEntry p in panelsForHalfScreen)
            {
                this.setPanelHalfHorizontalScreen((Panel)p.Value);
            }
        }

我该如何解决?

修改 alt text http://img519.imageshack.us/img519/3352/bb4u.jpg

1 个答案:

答案 0 :(得分:1)

你确定这行不会抛出ArgumentException吗?

this.panelsForHalfScreen.Add(p.Name,p);

如果key已经在Hashtable

中,则Add方法抛出ArgumentException