如何在 vb.net 中使用新的 vb6 集合

how to use new collection of vb6 in vb.net

我正在将 vb6 项目转换为 vb.net 但一直坚持这些

Private mCol As Collection

Public Property Get NewEnum() As IUnknown
    'this property allows you to enumerate
    'this collection with the For...Each syntax
    Set NewEnum = mCol.[_NewEnum]
End Property

Private Sub Class_Initialize()
    'creates the collection when this class is created
    Set mCol = New Collection
End Sub

我是 vb.net 的新手,所以我对这些工作一无所知 codes.Can 有人请向我解释它的工作原理以及我如何在 vb.net 中对其进行编码[= =14=]

这是收集的 vb6 函数

Public Function Add(Key As String, Optional sKey As String) As clsUser_Rights
    'create a new object
    Dim objNewMember As clsUser_Rights
    Set objNewMember = New clsUser_Rights

    'set the properties passed into the method
    objNewMember.Key = Key
    If Len(sKey) = 0 Then
        mCol.Add objNewMember
    Else
        mCol.Add objNewMember, sKey
    End If

    'return the object created
    Set Add = objNewMember
    Set objNewMember = Nothing
End Function

这就是我尝试过的

Private mCol As New Dictionary(Of string,string)

Public Function Add(Key As String, Optional sKey As String = "") As clsMsmt
    'create a new object
    Dim objNewMember As clsMsmt
    objNewMember = New clsMsmt

    'set the properties passed into the method
    objNewMember.Key = Key
    If sKey.Length = 0 Then
        mCol.Add(objNewMember)
    Else
        mCol.Add(objNewMember, sKey)
    End If

    'return the object created
    Add = objNewMember
    objNewMember = Nothing
End Function

您是否先尝试 google 您的问题?我想你没有。但无论如何,这里有一个提示:

' wrong: Dim mCcol As New Microsoft.VisualBasic.Collection()  

' correct: 
Dim mCcol As New Collection()  

抱歉,先在 C# 中尝试,在 VB.NET 中默认引用此程序集。

添加了新示例(在空 WinForm 中:)

    Dim dict As New Dictionary(Of String, String)
    dict.Add("KEY1", "dict: Some kind of stringdata")
    dict.Add("KEY2", "dict: other string data")
    dict.Add("KEY3", "dict: and finally: a string")

    For Each s As KeyValuePair(Of String, String) In dict
        MessageBox.Show(s.Value)
    Next

用您的类型 (clsMsmt) 替换定义中的第二个字符串

您突出显示的 VB6 代码看起来像是内置 Collection 类型的自定义包装器 class。枚举器部分是允许 For Each ... Next 在自定义集合上。

根据集合的用途 class,您可能在 .NET 中不需要它。在 VB6 中制作自定义集合 classes 的原因之一是提供类型安全,因为 Collection 只会提供 Object。对于此用途,您可以使用 List (Of T)Dictionary (Of TKey, TValue),具体取决于集合的使用方式。

如果集合中有额外的逻辑,您可能仍然坚持框架 classes 并添加一个或多个扩展方法来处理额外的逻辑,或者您可能继承自 Collection (Of T)KeyedCollection (Of TKey, TItem)。基础 classes 将提供集合样板逻辑,您可以专注于在继承的 class.

中提供额外的逻辑

如果使用 VB6 集合的代码由字符串和整数索引,那么您可能需要做更多的工作才能获得有效的 .NET 等价物,但我不希望这样(并且即使完成了,最可能的用例可能是删除项目,您可以重写它以正确使用字符串索引的 .NET 字典)。