【问题标题】:Exception: No default member found for type 'VB$AnonymousDelegate_0(Of String(),String,boolean)'.- Delegate function例外:没有找到类型“VB$AnonymousDelegate_0(Of String(),String,boolean)”的默认成员。- 委托函数
【发布时间】:2021-02-01 09:25:16
【问题描述】:

我在调用委托函数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

【问题讨论】:

  • 最初它调用正常但突然抛出这个异常No default member found for type 'VB$AnonymousDelegate_0(Of String(),String,Boolean).
  • 您应该明确声明函数委托:Dim isInventoryBook As Func(Of String(), String, Boolean) = Function(...)isInventoryBook 是否声明为局部变量?
  • @Jimi no isInventoryBook 不是局部变量。
  • 那么,它是一个实例字段吗?其他课程的一部分?无论如何,明确声明委托,否则它被推断为Object
  • 现在收到this 错误。哪些状态嵌套函数与委托没有相同的签名

标签: .net vb.net visual-studio-2015


【解决方案1】:

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

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

Local Type Inference:

本地类型推断适用于过程级别。它不能用于 在模块级别声明变量(在类、结构、模块中, 或接口,但不在过程或块内)

声明为字段:

' 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 InferOn 还是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

由于委托被声明为字段,请提供完整的声明:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-27
    • 2016-12-03
    • 2019-08-21
    • 2019-02-03
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-02-14
    相关资源
    最近更新 更多