gpt4 book ai didi

vbscript - 未命名的默认属性

转载 作者:行者123 更新时间:2023-12-03 06:36:56 26 4
gpt4 key购买 nike

在 VBScript 中,一些内置对象使用未命名的属性。一些例子:

Set Dict = Server.CreateObject("Scripting.Dictionary")
Set RS = GetEmloyeesRecordSet()

Dict("Beer") = "Tasty" ' Same as Dict.Item("Beer") = "Tasty"
Dict("Crude Oil") = "Gross" ' Same as Dict.Item("Crude Oil") = "Gross"

Response.Write "The First Employee Is: " & RS("Name") ' Same as RS.Fields("Name")

如何在我自己的类中使用相同的语法?

更新

这是一个关于如何执行此操作的独立工作示例,它是 Scripting.Dictionary 的简单包装器。请注意使用“Let”来允许 d("key") = "value"语法。当然,这要归功于 Thom 提供的答案。

<%
Class DictWrapper
Private Dict

Private Sub Class_Initialize()
Set Dict = Server.CreateObject("Scripting.Dictionary")
End Sub

Private Sub Class_Terminate()
Set Dict = Nothing
End Sub

Public Property Get Count
Count = Dict.Count
End Property

Public Default Property Get Item( Key )
Item = Dict(Key)
End Property

Public Property Let Item( Key, Value )
Dict(Key) = Value
End Property

Public Sub Add( Key, Value )
Dict.Add Key, Value
End Sub

End Class

Dim d : Set d = New DictWrapper
d.Add "Beer", "Good"
Response.Write d("Beer") & "<br>"
d("Beer") = "Bad"
Response.Write d("Beer")
%>

最佳答案

您需要将类的一个属性声明为默认属性。作为示例,这是我编写的 String 包装类的一部分:

class StringClass
private finished_
private data_
private size_

public function init (val)
finished_ = cStr(val)
set init = me
end function

public default property get value
if (size_ > 0) then
finished_ = finished_ & join(data_, vbNullString)
data_ = empty
size_ = 0
end if
value = finished_
end property

public property let value (val)
data_ = empty
size_ = empty
init(val)
end property

public function add (s)
size_ = size_ + 1
if (isEmpty(data_)) then
redim data_(MIN_ARRAY_SIZE)
elseif (size_ > uBound(data_)) then
redim preserve data_(Float(uBound(data_) * GRANTED_HEAD_ROOM).ceil)
end if
data_(size_ - 1) = cStr(s)
end function
end class

用法: 暗淡 s: 设置 s = 新 StringClass s()=“你好,世界!” ' s.value() = "你好,世界!" Response.Write ' Response.Write s.value()

您还可以拥有参数化的默认属性:

class ListClass
private size_
private data_

private sub CLASS_INITIALIZE
size_ = 0
data_ = Array()
resize_array MIN_ARRAY_SIZE
end sub

public default property get data (index)
if isObject(data) then
set data_(index) = data
else
data_(index) = data
end if
end property

public property let data (index, value)
data_(index) = value
end property

public property set data (index, value)
set data_(index) = value
end property

public function add(datum)
size_ = size_ + 1
if (size_ > uBound(data_) + 1) then expand_array

assign data_(size_ - 1), datum

add = datum
end function
end class

dim l: set l = new ListClass
l.add("Hello, world!")
l(0) = "Goodbye, world!"
Response.Write l(0)

第二个示例可能就是您正在寻找的,使用默认属性来实现集合,但值得查看第一个示例,使用默认属性来实现包装类的自动拆箱。

关于vbscript - 未命名的默认属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3187913/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com