2012-01-26 47 views
0

是否可以在模塊級別定義用戶定義的類型常量?類範圍內的常量UDT

Type MyType 
    name as String 
    description as String 
End Type 

' Something like this 
Private Const OneType as MyType = "Name" "Description" 

回答

2

不。Const不適用於用戶定義類型。你可以最接近的是創建一個只有屬性獲得的類。

Public Property Get Name() As String 
    Name = "Name" 
End Property 

Public Property Get Description() As String 
    Description = "Description" 
End Property 

如果你想有不同的值類的多個實例,但仍希望值是恆定的,然後添加只能使用一次的初始化程序。

Private sName As String 
Private sDescription As String 

Private Sub Class_Initialize() 
    sName = "" 
End Sub 

Public Sub Initialize(Name As String, Description As String) 
    If Len(sName) = 0 Then 
     sName = Name 
     sDescription = Description 
    Else 
     MsgBox "This instance of MyClass is already initialized!" 
    End If 
End Sub 

Public Property Get Name() As String 
    Name = sName 
End Property 
Public Property Get Description() As String 
    Description = sDescription 
End Property 

然後聲明你的類的一個實例。

Dim cMyClass1 As New MyClass, cMyClass2 as New MyClass 
cMyClass1.Initialize("Name","Description") 
cMyClass2.Initialize("DiffName","OtherDescription") 
+0

+1很好的例子 – brettdj 2012-01-27 07:05:53

+0

嘿謝謝你,我會那樣做的。 – Triztian 2012-01-27 21:17:27