VB.NET 我的数组循环出现 AmbiguousMatchException

VB.NET AmbiguousMatchException with my Array loop

每当我尝试使用此循环时,它都会崩溃并显示 AmbiguousMatchException,但是当我将其更改为 Do Until k = 2 时,代码运行没有问题。

Do Until k = 4
    i(k) = listview1.Items.Add(p(k, 0))
    With i(k)
        .SubItems.Add(p(k, 1))
        .SubItems.Add(p(k, 2))
        .SubItems.Add(p(k, 3))
        .SubItems.Add(p(k, 4))
    End With
    k = k + 1
Loop

我对 VB.NET 编码很陌生,但有人可以尝试在这里解释这个问题吗

我怀疑的原因是你在 p 中有一个不是字符串的值,甚至更多是 = Nothing。

示例:

Public Sub Bad()

    Dim listview1 As ListView = New ListView
    Dim t = Nothing
    Dim k As Integer = 0
    'Not Declared with a Type
    Dim p(,) = {{"string", "string", "string", "string", "string"}, _
                        {"string", "string", "string", "string", "string"}, _
                        {"string", "string", "string", "string", t}, _
                        {"10", "10", "test", "10", t}, _
                        {"10", "10", "test", "10", t}} 'Notice I added t as a value
    Dim i(4) As ListViewItem

    Do Until k = 4
        i(k) = listview1.Items.Add(p(k, 0))
        With i(k)
            .SubItems.Add(p(k, 1))
            .SubItems.Add(p(k, 2))
            .SubItems.Add(p(k, 3))
            .SubItems.Add(p(k, 4))
        End With
        k = k + 1
    Loop

End Sub

Public Sub Good()

    Dim listview1 As ListView = New ListView
    Dim t As String = Nothing
    Dim k As Integer = 0
    'Declared as String
    Dim p(,) As String = {{"string", "string", "string", "string", "string"}, _
                        {"string", "string", "string", "string", "string"}, _
                        {"string", "string", "string", "string", t}, _
                        {"10", "10", "test", "10", t}, _
                        {"10", "10", "test", "10", t}} 'Notice I added t as a value

    Dim i(4) As ListViewItem

    Do Until k = 4
        i(k) = listview1.Items.Add(p(k, 0))
        With i(k)
            .SubItems.Add(p(k, 1))
            .SubItems.Add(p(k, 2))
            .SubItems.Add(p(k, 3))
            .SubItems.Add(p(k, 4))
        End With
        k = k + 1
    Loop

End Sub

这两种方法之间的唯一区别是 P 被声明为 String 而另一个不是。当您添加一个尚未转换为 ToString 的值时,反射会最好地猜测该值的类型。如果反射无法确定过去的值类型,因为它匹配超过 1 种类型,则会抛出 AmbiguousMatchException。

所以在这种情况下,t = Nothing Nothing 的值可以等于任何类型的 pretty well anything。从下面的代码可以看出。

    Dim r = CType(Nothing, String)
    r = CType(Nothing, Integer)
    r = CType(Nothing, Object)
    r = CType(Nothing, Integer)

为了帮助避免这种情况,最好在第一行添加:

Option Strict On

它将禁止后期绑定,并禁止隐式键入