简体   繁体   中英

Anonymous functions in C#

The following syntax is valid VB.NET code

Dim myCollection As New List(Of Stock)
myCollection.Add(New Stock(Guid.NewGuid, "Item1"))
myCollection.Add(New Stock(Guid.NewGuid, "Item2"))

Dim res As List(Of Stock) = myCollection.FindAll(Function(stock As Stock) As Boolean
                                                     If stock.Description = "Item2" Then
                                                         Return True
                                                     End If
                                                     Return False
                                                 End Function)

How can I accomplish the same thing in C#? I have tried...

myCollection.FindAll(bool delegate(Stock stock) {
                        if (blah blah) {
                        }
                     });

But it appears I have somehow structured it incorrectly as I get the following error. "Error 1 Invalid expression term 'bool'"

You don't need the bool keyword. The return type is determined automatically based on the code in the anonymous function. Also, look into C# lambda expressions - it's a short-form of the same thing, and can be more clear than the traditional anonymous method.

Example of lambda usage:

myCollection.FindAll(stock => stock.Description == "Item2");

The following would be the equivalent C# code using a lambda expression

myCollection.FindAll((stock) => stock.Description == "Item2");

Using an anonymous function the above would be writen as follows

myCollection.FindAll(delegate(Stock stock) 
                     {
                       return stock.Description == "Item2";
                     });

You do not specify the return type for the anonymous function as you do in VB.NET

可以将其转换为lambda表达式。

myCollection.FindAll(s => s.Description == "Item2");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM