- Beginning C# 7 Hands-On:Advanced Language Features
- Tom Owsiak
- 395字
- 2021-07-02 15:29:23
Defining lambda expressions
Now, to define a lambda expression, you put = (a,b), as shown. Then this will be mapped to the operations that follow; so you think of => as the mapping symbol or mapping operator. It'll be mapped to the (a==b) operation. So, comp, in other words, will allow us to check whether the two values are the same, and that happens in the stage right where a and b are compared. Basically, (a, b) are the parameters, and the expression that is evaluated is whether a is equal to b.
Now, enter the following next:
sampLabel.Text = $"{x} and {y} are equal is {comp(x, y).ToString().ToLower()}";
To invoke this, note that you type comp and then pass in the x and y values. Then, to show that you can operate on this further, once you get a result from it, you can convert it, say, to a string version, and then all to lowercase, as shown in the preceding code line.
Remember, this is function chaining, so it goes from left to right as it executes. In other words, first comp runs, then ToString and lastly ToLower.
Also, note that, at runtime, when you pass in the x and y values when comp(x, y) is called, basically, it is (a==b) that will be hit; the comparison will be made, and the value will be sent back.
Next, we can also do the Multiply delegate, so enter the following below this line:
Multiply mult = (a, b) => (a * b);
Notice that (a,b) can be used and reused and so on. Remember that (a,b) here are parameters, and you can use them and reuse them. They're local within each of the lines where they appear. So, then you can use it in another one. Then, you say again that (a,b) maps to an operation of (a*b). Close this with a semicolon.
Now, to invoke this multiplication delegate (Lambda expression that it represents), copy (Ctrl + C) the sampLabel.Text line from above and paste it (Ctrl + V) down below, as shown here:
sampLabel.Text += $"<br>{x}*{y} is {mult(x, y).toString()}";
Here, we say {x}*{y} instead and then, += to append, and delete are equal, and replace comp with mult as the name of our object. You don't need toString for it to work, and since it'll give back a number, you don't need ToLower either.
- Python 3.7網絡爬蟲快速入門
- JavaScript 網頁編程從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- Android 9 Development Cookbook(Third Edition)
- 基于差分進化的優化方法及應用
- 編寫高質量代碼:改善C程序代碼的125個建議
- 琢石成器:Windows環境下32位匯編語言程序設計
- Learning Three.js:The JavaScript 3D Library for WebGL
- Visual FoxPro程序設計習題集及實驗指導(第四版)
- FPGA Verilog開發實戰指南:基于Intel Cyclone IV(進階篇)
- SQL Server 2016 從入門到實戰(視頻教學版)
- 實戰Python網絡爬蟲
- Learn Linux Quickly
- VMware vSphere Design Essentials
- Python深度學習(第2版)
- 產品架構評估原理與方法