2011-07-07 89 views
3

我想創建一個全局函數來在我的應用程序中使用。假設它是關於到數據庫的連接。vb.net - 全局函數

我的代碼,我計劃在我的全局函數使用的是:

myConnection = New SqlConnection("...........") 
myConnection.Open() 

所以,我可以把它在我的應用程序在任何形式的使用。這可以使我稍後輕鬆編輯連接。

任何人都可以幫助我展示如何定義這個全局函數以及如何在窗體中調用這個函數。

最佳方面,

+1

谷歌爲「共享」; o) –

+1

有關使用共享成員的模塊與類的討論,請參閱:http://stackoverflow.com/questions/881570/classes-vs-modules-in-vb-net – Heinzi

回答

2

使用模塊而不是類

Module ConnectionHelper 
    Public Function OpenConnection() As SqlConnection 
     Dim conn As New SqlConnection("") 
     conn.Open() 
     Return conn 
    End Function 
End Module 

Class P 
    Public Sub New() 
     Using conn = OpenConnection() 
      'here you can work with connection 
     End Using 
    End Sub 
End Class 

在P級你有首選使用的展示

4
Public NotInheritable Class Utilities 

Private Sub New() 
End Sub 

Public Shared Function MyMethod(myParam As Object) As MyObject 
    'Do stuff in here 
    Return New MyObject() 
End Function 

End Class 

然後消耗

Dim instance As MyObject = Utilities.MyMethod(parameterObject)