我找到了一种在VBScript中扩展类的方法,但有没有办法传入参数或重载构造函数?我目前正在使用Init函数来初始化属性,但是我希望能够在创建对象时执行此操作.
这是我的示例类:
Class Test
Private strText
Public Property Get Text
Text = strText
End Property
Public Property Let Text(strIn)
strText = strIn
End Property
Private Sub Class_Initialize()
Init
End Sub
Private Sub Class_Terminate()
End Sub
Private Function Init
strText = "Start Text"
End Function
End Class
Run Code Online (Sandbox Code Playgroud)
我创造了它
Set objTest = New Test
Run Code Online (Sandbox Code Playgroud)
但是想做这样的事情
Set objTest = New Test(strInitText)
Run Code Online (Sandbox Code Playgroud)
这是可能的,还是必须在两个setps中创建和初始化对象?
jam*_*mus 22
只是稍微改变一下svinto的方法......
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")
Run Code Online (Sandbox Code Playgroud)
我是怎么做的 可悲的是,没有超负荷.
[编辑]虽然如果你真的想要你可以做这样的事......
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
Run Code Online (Sandbox Code Playgroud)
这给了施工人员......
Test()
Test(string)
Test(integer)
Test(string, integer)
Run Code Online (Sandbox Code Playgroud)
你可以称之为:
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))
Run Code Online (Sandbox Code Playgroud)
虽然有点痛苦.
您可以通过让Init函数返回对象本身来解决它...
Class Test
Private m_s
Public 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).Init("hello world")
Echo o.Hello
Run Code Online (Sandbox Code Playgroud)