Overload constructors in VBScript

后端 未结 4 1940
逝去的感伤
逝去的感伤 2021-01-31 21:13

I found a way to extend classes in VBScript, but are there any ways to pass in parameters or overload the constructor? I am currently using an Init function to initialize the p

4条回答
  •  死守一世寂寞
    2021-01-31 21:35

    Just to alter slightly on svinto's method...

    Class Test
      Private m_s
      Public Default Function Init(s)
        m_s = s
        Set Init = Me
      End Function
      Public Function Hello()
        Hello = m_s
      End Function
    End Class
    
    Dim o : Set o = (New Test)("hello world")
    

    Is how I do it. Sadly no overloading though.

    [edit] Though if you really wanted to you could do something like this...

    Class Test
        Private m_s
        Private m_i
    
        Public Default Function Init(parameters)
             Select Case UBound(parameters)
                 Case 0
                    Set Init = InitOneParam(parameters(0))
                 Case 1
                    Set Init = InitTwoParam(parameters(0), parameters(1))
                 Else Case
                    Set Init = Me
             End Select
        End Function
    
        Private Function InitOneParam(parameter1)
            If TypeName(parameter1) = "String" Then
                m_s = parameter1
            Else
                m_i = parameter1
            End If
            Set InitOneParam = Me
        End Function
    
        Private Function InitTwoParam(parameter1, parameter2)
            m_s = parameter1
            m_i = parameter2
            Set InitTwoParam = Me
        End Function
    End Class
    

    Which gives the constructors...

    Test()
    Test(string)
    Test(integer)
    Test(string, integer)
    

    which you can call as:

    Dim o : Set o = (New Test)(Array())
    Dim o : Set o = (New Test)(Array("Hello World"))
    Dim o : Set o = (New Test)(Array(1024))
    Dim o : Set o = (New Test)(Array("Hello World", 1024))
    

    Bit of a pain though.

提交回复
热议问题