全局變量的定義和使用

字號:

在用VB開發(fā)軟件時,經(jīng)常需要在不同的窗體間共享數(shù)據(jù),但在過多的使用全局變量時不便于軟件的調(diào)試和修改。通常有兩種解決方法。
    第一種方法:定義全局變量,然后在各個窗體中直接使用,例如
    Public strCustomerID As String
    Public strCustomerName As String
    第二種方法:添加一個模塊專門用于定義變量,然后定義一些Public過程或函數(shù)來設(shè)置和獲取這些數(shù)據(jù),例如
    Dim strCustomerID As String
    Dim strCustomerName As String
    Public Sub SetCustomerID(CustomerID As String)
    strCustomerID = CustomerID
    End Sub
    Public Function GetCustomerID() As String
    GetCustomerID = strCustomerID
    End Function
    Public Sub SetCustomerName(CustomerName As String)
    strCustomerName = CustomerName
    End Sub
    Public Function GetCustomerName() As String
    GetCustomerName = strCustomerName
    End Function
    考試大提醒:其實這兩種方法都有缺點,使用第一種方法時,當(dāng)過程或函數(shù)中過于頻繁的使用全局變量時會給調(diào)試和修改程序帶來很大的工作量,有時會產(chǎn)生災(zāi)難性的后果。使用第二種方法時,若共享數(shù)據(jù)很多,則需要定義很多的Set*和Get*函數(shù)。