异常:找不到类型"VB$AnonymousDelegate_0(字符串(),字符串,布尔值)"的默认成员。 委托函数



我在调用委托函数isInventoryBook时遇到了此异常。错误信息显示,No default member found for type 'VB$AnonymousDelegate_0(Of String(),String,Boolean)'.

我的代码如下所述:

If isInventoryBook(InvBooksArr, "DCLL.") Then
If chk.Value = True Then
chk.Value = False
Else
chk.Value = True
End If
End If
  • 主叫委托功能:
Dim isInventoryBook = Function(arr As String(), temp As String) As Boolean
Return arr.Contains(temp)
End Function

由于函数委托没有声明为局部变量,而是作为实例字段,因此类型推断以不同的方式工作。

这在Visual Basic语言文档中有描述:

本地类型推断:

局部类型推断应用于过程级。它不能被习惯在模块级声明变量(在类、结构、模块、或接口(但不在过程或块中)

声明为字段:

' This is inferred as Object
Public Class SomeClass
Private isInventoryBook = 
Function(arr As String(), temp As String) As Boolean
Return arr.Contains(temp)
End Function
' [...]
End Class

函数委托被推断为Object,无论Option Infer是On还是Off

如果委托是在过程级声明的,并且Option InferOn,那么委托和它的返回类型就会被推断出来。

Private Sub SomeMethod()

' This is inferred as Function(Of String(), String, Boolean) 
Dim isInventoryBook =
Function(arr As String(), temp As String) As Boolean
Return arr.Contains(temp)
End Function
' [...]       
If isInventoryBook(someArray, "SomeValue") Then
' [...]
End If
End Sub

由于委托被声明为Field,因此提供完整的声明:

Public Class SomeClass
Private isInventoryBook As Func(Of String(), String, Boolean) =
Function(arr As String(), temp As String) As Boolean 
Return arr.Contains(temp) 
End Function
' [...]
End Class

将选项严格设置为On将通知不允许此字段声明,并且还清楚地表明委托被视为Object类型,而不是函数。

Option InferOption Strict可以通过不同的方式预先设置:

  • 作为Visual Studio选项工具的默认值:
    Tools -> Options -> Projects and Solution -> VB Defaults
  • 项目级:
    Project -> Properties -> Compile
  • 你也可以在类/模块级别设置选项(如果你不想重构你的整个项目,如果你使用Option Strict Off作为默认设置,它可能是有用的):
    添加每个Option在文件的顶部

最新更新