类模块范围实例化和重用
默认情况下,新的类模块是 Private 类,因此它仅可用于实例化并在定义它的 VBProject 中使用。你可以在同一个项目中的任何位置声明,实例化和使用该类 :
'Class List has Instancing set to Private
'In any other module in the SAME project, you can use:
Dim items As List
Set items = New List
但是,你通常会编写你希望在其他项目中使用的类,而无需在项目之间复制模块。如果你在 ProjectA 中定义一个名为 List 的类,并想在 ProjectB 中使用该类,那么你需要执行 4 个动作:
-
在属性窗口中更改
List中List类的实例属性,从Private到PublicNotCreatable -
在
ProjectA中创建一个公共工厂功能,创建并返回List类的实例。通常,工厂函数将包含用于初始化类实例的参数。工厂函数是必需的,因为ProjectB可以使用该类,但是ProjectB不能直接创建ProjectA类的实例。Public Function CreateList(ParamArray values() As Variant) As List Dim tempList As List Dim itemCounter As Long Set tempList = New List For itemCounter = LBound(values) to UBound(values) tempList.Add values(itemCounter) Next itemCounter Set CreateList = tempList End Function -
在
ProjectB中,使用Tools..References...菜单添加对ProjectA的引用。 -
在
ProjectB中,声明一个变量并使用ProjectA的工厂函数为其分配一个List的实例Dim items As ProjectA.List Set items = ProjectA.CreateList("foo","bar") 'Use the items list methods and properties items.Add "fizz" Debug.Print items.ToString() 'Destroy the items object Set items = Nothing