AndFunc2
(私のオリジナル)は正常に動作しますが、何らかの理由で「型のオブジェクトを型にキャストできません」というランタイムが生成されることを理解できませAndFunc
ん」InvalidCastException
VB$AnonymousDelegate_3 2'[System.Int32,System.Boolean]
System.Func'2[System.Int32,System.Boolean]
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