带有选项脚本的Scripting.Dictionary不允许后期绑定

时间:2018-12-04 21:09:04

标签: vb.net vb6-migration

我已经将VB6代码迁移到Vb.Net并转为Option strict On

现在,.Keys(intIndex)引发异常Option Strict On disallows late binding。下面是代码:

Public Function PopulateList(ByRef dicListValues As Scripting.Dictionary)
    Dim strKey As String
    With dicListValues
        For intIndex = 0 To .Count - 1
            strKey = .Keys(intIndex)
        Next
    End With

2 个答案:

答案 0 :(得分:1)

这就是为什么您不想使用Scripting.Dictionary

Dim dict As Scripting.Dictionary = New Scripting.DictionaryClass()
dict.Add("1", 1)
dict.Add(2, "2")
dict.Add(Math.PI, "a")
dict.Add(New Text.StringBuilder(), "builder")
For i = 0 To dict.Count - 1
    Console.WriteLine("Key: {0}, Value: {1}", dict.Keys(i), dict(dict.Keys(i)))
Next

您会看到dict.Keys(i)dict(dict.Keys(i))(字典的键和值)可以是任何类型的对象(每种类型)。

好的,假设您拥有所有字符串。

Dim strKey As String
With dicListValues
    For intIndex = 0 To .Count - 1
        strKey = .Keys(intIndex).ToString()
    Next
End With

(您可以仅通过添加字符串来控制它,但是除非您注释良好,否则这是不明显的)。

更好的解决方案是在整个项目中用Dictionary(Of TKey, TValue)替换Scripting.Dictionary。您可以使用Convert VB6 Scripting.Dictionary to .NET Generic Dictionary

之前我评论的链接将Scripting.Dictionary转换为它们。

答案 1 :(得分:0)

如果您要使用Scripting.Dictionary在选项strict选项启用时工作,这就是答案。

    Dim dict As New Scripting.Dictionary '= New Scripting.DictionaryClass()
    Dim str As String
    dict.Add("1", 10)
    dict.Add(2, "20")
    dict.Add(Math.PI, "Test")

    dict.Add(New Text.StringBuilder(), "builder")
    For i = 0 To dict.Count - 1
        str = CType(DirectCast(dict.Keys, Object())(i), String)
    Next