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 :(得分:1)
“函数()到Func”不是精确的隐式转换,而是Func
期望的正常分配(即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