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