2013-07-24 103 views
0

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 
+0

只是出於好奇,你想要什麼代碼?爲什麼使它變得如此不必要地滲透?它實際上是要麼還是隻是爲了證明/理解/測試一個觀點? – varocarbas

+0

我正在使用這些來構建'IEnumerable.Where()'過濾器函數,它由幾個可選部分組成(基本上是搜索選項)。 'AndFunc'絕對有用。儘管如此,還沒有用於其他布爾比較。我仍然非常想知道爲什麼這不起作用,並把它放在我的袖子裏。 –

回答

1

「功能()的功能」是不準確的隱式轉換,但正常的分配其中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 
+0

啊,我完全掩飾了包括返回類型!我認爲我的大腦被第三個參數的相同簽名所欺騙......另一個VB.NET的「簡單性」是它自己最大的敵人。 –

+0

@ j.i.h。這是絕對正常的(不是在談論VB.NET的特性,而是你錯過了這一點),你的代碼非常複雜;這就是爲什麼我問你這樣做的原因:如此複雜的代碼在調試時會帶來很多問題。 – varocarbas

相關問題