1

AndFunc2(我原来的)工作正常,但由于某种原因,我不明白会AndFunc生成InvalidCastException“无法将类型的对象强制转换VB$AnonymousDelegate_3 2'[System.Int32,System.Boolean]为类型System.Func'2[System.Int32,System.Boolean]”的运行时

Function()这种对 a 的隐式转换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
4

1 回答 1

1

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

您没有在 中包含该As Func(Of T, Boolean)BoolFunc,是什么使该函数“匿名”(您没有明确表示返回的类型)。包括这个位,它应该可以正常工作。也就是说,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
于 2013-07-24T14:56:30.173 回答