2017-09-30 68 views
0

我有一個功能,它看起來像這樣:如何將表單作爲函數參數傳遞?

Function SpawnForm(Form) 
    Dim Spawn As New Form With {.TopLevel = False, .AutoSize = False} 
    Try 
     Spawn.Dock = DockStyle.Fill 
     MainForm.SpawnPanel.Controls.Add(Spawn) 
     Spawn.Show() 
    Catch ex As Exception 
     MsgBox(ex.Message) 
    End Try 
    Return Nothing 
End Function 

我想將參數傳遞到函數的其餘部分,所以如果我要稱呼其爲這樣:

SpawnForm(SettingsForm) 

它然後會在我的項目中生成名爲SettingsForm的現有表單。

我知道這個問題是這樣的:

Dim Spawn As New Form 

我應該怎麼做不同的傳遞參數?

回答

1

您可以製作一些具有一定約束條件的泛型函數。這允許您在方法內部保留表單創建(而不是傳遞實例)。也從函數返回實例。

Private Function SpawnForm(Of T As {New, Form})() As T 
    Dim spawn As New T() With {.TopLevel = False, .AutoSize = False} 
    Try 
     spawn.Dock = DockStyle.Fill 
     MainForm.SpawnPanel.Controls.Add(spawn) 
     spawn.Show() 
    Catch ex As Exception 
     MsgBox(ex.Message) 
    End Try 
    Return spawn 
End Function 

用法:

Dim mySettingsForm = SpawnForm(Of SettingsForm)() 
相關問題