Guide to the Language
Download 2 Mb. Pdf ko'rish
|
C sharp
- Bu sahifa navigatsiya:
- Lambda Expressions
Anonymous Methods
C# 2.0 also introduced anonymous methods, which can be assigned to delegate objects. An anonymous method is specified by using the delegate keyword followed by a method parameter list and body. This can simplify the delegate’s instantiation since a separate method will not have to be defined in order to instantiate the delegate. MyDelegate f = delegate(string s) { System.Console.WriteLine(s); }; Chapter 26 Delegates 147 Lambda Expressions C# 3.0 went one step further and introduced lambda expressions. They achieve the same goal as anonymous methods, but with a more concise syntax. A lambda expression is written as a parameter list followed by the lambda operator (=>) and an expression. delegate int MyDelegate(int i); static void Main() { // Anonymous method MyDelegate a = delegate(int x) { return x * x; }; // Lambda expression MyDelegate b = (int x) => x * x; a(5); // 25 b(5); // 25 } The lambda must match the signature of the delegate. Typically, the compiler can determine the data type of the parameters from the context, so they do not need to be specified. The parentheses may also be left out if the lambda has only one input parameter. MyDelegate c = x => x * x; If no input parameters are needed, an empty set of parentheses must be specified. delegate void MyEmptyDelegate(); // ... MyEmptyDelegate d = () => System.Console.WriteLine("Hello"); Chapter 26 Delegates 148 A lambda expression that only executes a single statement is called an expression lambda. The expression of a lambda can also be enclosed in curly brackets to allow it to contain multiple statements. This form is called a statement lambda. MyDelegate e = (int x) => { int y = x * x; return y; }; Download 2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling