有没有一种方法重载的构造函数/在VBA类初始化程序? [英] Is there a way to overload the constructor / initialize procedure for a class in VBA?
问题描述
在C#中,我知道我可以在类的主体指定它重载一类的构造函数:
In C#, I know that I can overload the constructor for a class by specifying it in the body of the class:
public class MyClass()
{
public MyClass(String s) { ... }
}
这将覆盖默认的构造函数(没有参数),并迫使类与参数S被初始化。
This overrides the default constructor (which has no parameters) and forces the class to be initialized with parameter s.
我知道,在VBA我可以初始化我与类私人小组Class_Initialize()
,但我不知道是否有办法迫使我的课与参数进行初始化。可以这样做?
I know that in VBA I can initialize my class with Private Sub Class_Initialize()
, but I don't know if there's a way to force my class to be initialized with parameters. Can this be done?
推荐答案
由于Jtolle指出,这是根本不可能在VBA / VB6。有没有要解决这一点,但完美的方法,是我亲手做的是创建一个公共/朋友分电话与我想要的参数初始化(在VBA / VB6您使用重载可选的参数),然后放在一个快速检查所有外露如果您尝试访问它们而不运行初始化方法抛出异常类的成员。一个基本的例子可能是这样的:
As Jtolle indicated, this is simply not possible in VBA/VB6. There is no perfect way to work around this but, what I personally do is create a Public/Friend sub call Initialize with the parameters I want (in VBA/VB6 you use "Optional" parameters for overloading) and then put a quick check in all exposed members of the class that throws an exception if you try to access them without running the initialize method. A basic example might look like this:
Option Explicit
Private m_blnInitialized As Boolean
Private m_lngID As Long
Private m_strFirstName As String
Public Sub Initialize(ByVal ID As Long, Optional ByVal someOtherThing As String = vbNullString)
If m_blnInitialized Then Me.Clear
m_lngID = ID
m_strFirstName = SomeLookUp()
If LenB(someOtherThing) Then
''Do something here.
End If
m_blnInitialized = True
End Sub
Public Property Get ID() As Long
If Not m_blnInitialized Then Err.Raise eStandardErrors.eNotInitialized
ID = m_lngID
End Property
Public Property Get FirstName() As String
If Not m_blnInitialized Then Err.Raise eStandardErrors.eNotInitialized
FirstName = m_strFirstName
End Property
Private Function SomeLookUp() As String
''perform magic on Me.ID
End Function
Public Sub LoadPicture()
If Not m_blnInitialized Then Err.Raise eStandardErrors.eNotInitialized
''More magic
End Sub
Public Sub Clear()
If Not m_blnInitialized Then Err.Raise eStandardErrors.eNotInitialized
m_strFirstName = vbNullString
m_lngID = 0&
m_blnInitialized = False
End Sub
这是不是很大,但它是我们所好,因为它会得到使用VBA / VB6。
It's not great, but it's about as good as it's going to get with VBA/VB6.
这篇关于有没有一种方法重载的构造函数/在VBA类初始化程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!