2017-03-09 27 views
-1

我通常用下面的代碼顯示形式:如何爲show表單創建一個通用函數?

frmEmployeeManage em = null; 
private void ShowEmployee_Click(object sender, EventArgs e) 
    { 

     if (em == null || em.IsDisposed) 
     { 
      em = new frmEmployeeManage(); 
      em.MdiParent = this; 
      em.FormBorderStyle = FormBorderStyle.None; 
      em.WindowState = FormWindowState.Maximized; 
      em.Show(); 
     } 
     else 
     { 
      em.Activate(); 
     } 
    } 

現在我想寫顯示形式的函數。下面的代碼我不知道如何將一個表單類作爲參數傳遞給函數。

class CommonService 
{ 
    public static void ShowFrom(Form frmChild, Form frmParent) 
    { 
    if (frmChild == null || frmParent.IsDisposed) 
    { 
     frmChild = new Form(); // How passing the form class here? 
     frmChild.MdiParent = frmParent; 
     frmChild.FormBorderStyle = FormBorderStyle.None; 
     frmChild.WindowState = FormWindowState.Maximized; 
     frmChild.Show(); 
    } 
    else 
    { 
     frmParent.Activate(); 
    } 
    } 
} 

最後我用show形式的功能,如下面的例子:

frmEmployeeManage em = null; 
CommonService.ShowForm(frmEmployee, this); 
+2

出了什麼問題? – Berkay

回答

1

我想你需要的是使用ref參數:

public static void ShowFrom<T>(ref T frmChild, Form frmParent) where T : Form, new() 
    { 
    if (frmChild == null || frmParent.IsDisposed) 
    { 
     frmChild = new T(); // How passing the form class here? 
     frmChild.MdiParent = frmParent; 
     frmChild.FormBorderStyle = FormBorderStyle.None; 
     frmChild.WindowState = FormWindowState.Maximized; 
     frmChild.Show(); 
    } 
    else 
    { 
     frmParent.Activate(); 
    } 
    } 

,並調用它像這樣:

frmEmployeeManage em = null; 
CommonService.ShowForm(ref em, this); 

ref允許您更改方法中參數的值,並且這些更改也反映在傳入的變量中。

+0

@rene編輯。多麼愚蠢的錯誤! – Sweeper

+0

非常感謝! – Vincent

相關問題