Proper way to dispose a new Form

前端 未结 4 2056
囚心锁ツ
囚心锁ツ 2020-11-27 22:15

So in my apps, I tend to create new instances of forms on the fly, then use Form.Show() to display them (non modal).



        
4条回答
  •  遥遥无期
    2020-11-27 22:54

    You could implement somekind of forms manager that will subscribe to the OnFormClosedEvent for each form it shows, it can then dispose them... something like:

    public class FormManager
    {
        public T ShowForm()
            where T : Form, new()
        {
            var t = new T();
            t.OnFormClosing += DisposeForm;
            return t;
        }
    
        void DisposeForm(object sender, FormClosedEventArgs args)
        {
            ((Form)sender).Dispose();
        }
    }
    

    You could even go so far as to implement IDisposable and dispose all non-disposed forms when the manager is disposed :)

提交回复
热议问题