13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

238 CHAPTER 9 Lambda expressions and expression trees{str<strong>in</strong>g name = prop.DisplayName;object value = prop.GetValue(e);Console.WriteL<strong>in</strong>e(" {0}={1}", name, value);}}...Button button = new Button();button.Text = "Click me";button.Click += (src, e) => { Log("Click", src, e); };button.KeyPress += (src, e) => { Log("KeyPress", src, e); };button.MouseClick += (src, e) => { Log("MouseClick", src, e); };Form form = new Form();form.AutoSize=true;form.Controls.Add(button);Application.Run(form);List<strong>in</strong>g 9.5 uses lambda expressions to pass the event name and parameters to the Logmethod, which logs details of the event. We don’t log the details of the source event,beyond whatever its ToStr<strong>in</strong>g override returns, because there’s an overwhelm<strong>in</strong>gamount of <strong>in</strong>formation associated with controls. However, we use reflection over propertydescriptors to show the details of the EventArgs <strong>in</strong>stance passed to us. Here’ssome sample output when you click the button:Event: ClickSender: System.W<strong>in</strong>dows.Forms.Button, Text: Click meArguments: System.W<strong>in</strong>dows.Forms.MouseEventArgsButton=LeftClicks=1X=53Y=17Delta=0Location={X=53,Y=17}Event: MouseClickSender: System.W<strong>in</strong>dows.Forms.Button, Text: Click meArguments: System.W<strong>in</strong>dows.Forms.MouseEventArgsButton=LeftClicks=1X=53Y=17Delta=0Location={X=53,Y=17}All of this is possible without lambda expressions, of course—but it’s a lot neater than itwould have been otherwise. Now that we’ve seen lambdas be<strong>in</strong>g converted <strong>in</strong>to delegate<strong>in</strong>stances, it’s time to look at expression trees, which represent lambda expressionsas data <strong>in</strong>stead of code.9.3 Expression treesThe idea of “code as data” is an old one, but it hasn’t been used much <strong>in</strong> popular programm<strong>in</strong>glanguages. You could argue that all .NET programs use the concept,because the IL code is treated as data by the JIT, which then converts it <strong>in</strong>to nativeLicensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!