VB.NET AmbiguousMatchException与我的数组循环



每当我尝试使用这个循环时,它都会崩溃并显示一个AmbiguousMatchException,但是当我将其更改为Do直到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反射会对值的类型做出最好的猜测。如果反射因为匹配了不止一种类型而无法找出过去的值的类型,则抛出AmbiguousMatchException。

在这种情况下,t = Nothing的值Nothing可以等于任何类型。如下面的代码所示:

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

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

Option Strict On

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

相关内容

  • 没有找到相关文章

最新更新