无法将VB$AnonymousDelegate类型的对象强制转换为System.Func类型



AndFunc2(我的原始版本)运行良好,但由于某种原因,我不理解AndFunc生成"无法将类型为'VB$AnonymousDelegate_3 2'[System.Int32,System.Boolean]的对象强制转换为类型为System.Func'2[System.Int32,System.Boolean]"的运行时InvalidCastException

Function()Func的这种隐式转换通常对我有效,但这次不行。我想知道为什么会这样,是否有一种方法可以明确地解决这个问题?

对于记录,这在VB.NET 2008和VB.NET 2012中以相同的方式失败。

Sub Main()
    Console.WriteLine("My func: " & AndFunc2(Function(a As Integer) First(a), Function(b) Second(b))(5))
    Console.WriteLine("My func: " & AndFunc(Function(a As Integer) First(a), Function(b) Second(b))(5))
End Sub
Function First(ByVal a As Integer) As Boolean
    Console.WriteLine(a)
    Return False
End Function
Function Second(ByVal a As Integer) As Boolean
    Console.WriteLine(a)
    Return False
End Function
<System.Runtime.CompilerServices.Extension()> _
Public Function AndFunc(Of T)(ByVal f1 As Func(Of T, Boolean), ByVal f2 As Func(Of T, Boolean)) As Func(Of T, Boolean)
    Return BoolFunc(Of T)(Function(b1 As Boolean, b2 As Boolean) b1 AndAlso b2, f1, f2)
End Function
Public Function BoolFunc(Of T)(ByVal bfunc As Func(Of Boolean, Boolean, Boolean), ByVal f1 As Func(Of T, Boolean), ByVal f2 As Func(Of T, Boolean))
    If f1 Is Nothing Then Return f2
    If f2 Is Nothing Then Return f1
    Return Function(param As T) bfunc(f1(param), f2(param))
End Function
<System.Runtime.CompilerServices.Extension()> _
Public Function AndFunc2(Of T)(ByVal f1 As Func(Of T, Boolean), ByVal f2 As Func(Of T, Boolean)) As Func(Of T, Boolean)
    If f1 Is Nothing Then Return f2
    If f2 Is Nothing Then Return f1
    Return Function(param As T) f1(param) AndAlso f2(param)
End Function

"Function()to a Func"不是精确的隐式转换,而是Func所期望的正常赋值(即Function)。

您没有在BoolFunc中包含As Func(Of T, Boolean)位,这使得该函数"匿名"(您没有明确表示返回的类型)。包括这一点,它应该工作没有任何问题。也就是说,将您的BoolFunc替换为以下内容:

Public Function BoolFunc(Of T)(ByVal bfunc As Func(Of Boolean, Boolean, Boolean), ByVal f1 As Func(Of T, Boolean), ByVal f2 As Func(Of T, Boolean)) As Func(Of T, Boolean)
    If f1 Is Nothing Then Return f2
    If f2 Is Nothing Then Return f1
    Return Function(param As T) bfunc(f1(param), f2(param))
End Function

最新更新