Does VB.NET and Visual Studio 2010 support multiline anonymous method?
I found that this answer was asked and answered before VS2010 was actually released.
They say that
VB9 has only single-line anonymous functions. We're adding full statement and multi-line lambdas in VB10.
But I tried to add this code
Dim test2 = Function(t1 As T, t2 As T) (
Dim val1 As IComparable = DirectCast(prop.GetValue(t1), IComparable)
Dim val2 As IComparable = DirectCast(prop.GetValue(t2), IComparable)
Return val1.CompareTo(val2)
)
to a .NET Framework 4.0 project in Visual Studio 2010 and it d开发者_如何学运维oes not compile.
Do you now if this feature is really implemented and what I am doing wrong?
I believe you are only missing your 'End Function' line. Try this:
Dim test2 = (Function(t1 As T, t2 As T)
Dim val1 As IComparable = DirectCast(prop.GetValue(t1), IComparable)
Dim val2 As IComparable = DirectCast(prop.GetValue(t2), IComparable)
Return val1.CompareTo(val2)
End Function)
You are missing End Function
and you are trying to enclose the function body in parenthesis, which is wrong. This should work:
Dim test2 = Function(t1 As T, t2 As T)
Dim val1 As IComparable = DirectCast(prop.GetValue(t1), IComparable)
Dim val2 As IComparable = DirectCast(prop.GetValue(t2), IComparable)
Return val1.CompareTo(val2)
End Function
This feature is documented here:
- Lambda Expressions (Visual Basic)
Here is something you might find useful. Note how the method declared is instantly invoked.
Dim food = New With {
.ID = 1,
.Name = "Carrot",
.Type = (
Function(name As String)
If String.IsNullOrEmpty(name) Then Return String.Empty
Select Case name.ToLower()
Case "apple", "tomato": Return "Fruit"
Case "potato": Return "Vegetable"
End Select
Return "Meat"
End Function
)(.Name)
}
Dim type = food.Type
精彩评论