总的来说,我是 VB 的新手。我正在浏览一些旧的 VB 代码,我看到类似这样的语句 -
Addr.AddrType(CStr(0)).A_Type = " "
为什么整数0一定要转成字符串?
注意Addr定义为
Public Addr As clsAddressDetail
AddrType 被定义为一个集合
Public AddrType As New Collection
最佳答案
这里使用的 Collection
类实际上是一个 overloaded indexer。 .我的重点:
Returns a specific element of a Collection object either by position or by key. Read-only.
Default Public ReadOnly Property Item( _ ByVal { Key As String | Index As Integer | Index As Object } _ ) As Object
Parameters
Key
A unique String expression that specifies a key string that can be used, instead of a positional index, to access an element of the collection. Key must correspond to the Key argument specified when the element was added to the collection.
Index
(A) A numeric expression that specifies the position of an element of the collection. Index must be a number from 1 through the value of the collection's Count Property (Collection Object). Or (B) An Object expression that specifies the position or key string of an element of the collection.
因此,如果您请求 AddrType(0)
,则您请求的是集合的第零个成员,对于这个基于 1 的集合来说这是一个错误。但是,如果您请求 AddrType("0")
,则您请求的是使用 Key "0"
添加的成员。任何字符串都可以用作键 - 只是这里使用的特定字符串是数字的字符串表示。
顺便说一句,从风格上来说,我会说写 CStr(0)
而不是 "0"
并不是特别好......
关于collections - 为什么整数必须先转换为字符串才能用于访问集合中的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10230220/