有没有办法在 VBA 中重载类的构造函数/初始化过程?

有没有办法在 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 中我可以用 Private Sub 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 中根本不可能.没有完美的方法可以解决这个问题,但是,我个人所做的是使用我想要的参数创建一个公共/朋友子调用 Initialize(在 VBA/VB6 中,您使用可选"参数进行重载),然后快速检查如果您尝试在不运行 initialize 方法的情况下访问它们,则会引发异常的类的所有公开成员.一个基本示例可能如下所示:

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.