每当我尝试使用此循环时,它会崩溃并显示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编码很新,但有人可以尝试解释这里的问题
答案 0 :(得分:1)
我怀疑你的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
2个方法之间的唯一区别是P被声明为String而另一个不是。当您添加尚未转换的值时,ToString Reflection会对值的类型进行最佳猜测。如果反射无法确定过去的值是什么类型,因为它匹配多于1个类型,则抛出AmbiguousMatchException。
所以在这种情况下,t = Nothing Nothing的值可以等同于任何类型。正如您从下面的代码中看到的那样。
Dim r = CType(Nothing, String)
r = CType(Nothing, Integer)
r = CType(Nothing, Object)
r = CType(Nothing, Integer)
为了避免这种情况,最好在第一行添加:
Option Strict On
它将禁止后期绑定,并且不允许隐式输入