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
只是出於好奇,你想要什麼代碼?爲什麼使它變得如此不必要地滲透?它實際上是要麼還是隻是爲了證明/理解/測試一個觀點? – varocarbas
我正在使用這些來構建'IEnumerable.Where()'過濾器函數,它由幾個可選部分組成(基本上是搜索選項)。 'AndFunc'絕對有用。儘管如此,還沒有用於其他布爾比較。我仍然非常想知道爲什麼這不起作用,並把它放在我的袖子裏。 –