C# Event--Anonymous Methods

本文介绍了C#中匿名方法的应用,展示了如何在ASP.NET页面中使用匿名方法处理按钮点击事件,以及如何通过匿名方法启动新的线程。文章还讨论了匿名方法内部实现的细节,并提醒开发者注意代码清晰度。

Anonymous methods are another improvement of the next generation of C#. They allow you to declare methods in the context of their use and without naming them.

Listing 1-12 demonstrates the use of anonymous methods within an ASP.NET page. During Page_Load an anonymous event-handling method is assigned to a Button control. The method will change the text of the Label control, which is also placed on the page.



Listing 1-12:
Assigning and Handling Events Right Away

  1. void Page_Load (object sender, System.EventArgs e)
  2. {
  3.    this.Button1.Click += delegate(object dlgSender, EventArgs dlgE)
  4.    {
  5.      Label1.Text = "Yeah, you clicked the button!";
  6.    };
  7. }

What's new is that you can abandon an explicit notation of the event-handling method—as long as it's useful! Just put the code after the assignment of the delegate. Open a new scope after the delegate keyword by using a brace, enter the desired actions, and close the scope with another brace. Then you finish the whole statement with a semicolon.

Unlike what is being demonstrated in the previous example, you can use more than one line of code, of course. In doing so, you have access to the two common event parameters that have to be defined explicitly as you assign the delegate. Please notice that I've renamed these parameters to avoid a conflict with the ones for the Page_Load event.

Even if it looks somewhat unusual at first sight, it's possible to use the local variables of the outer scope within the anonymous method. According to this, the lines in Listing 1-13 are correct, although they aren't arranged very clearly.



Listing 1-13: Accessing Variables Declared in the Upper Scope


  1. void Page_Load (object sender, System.EventArgs e)
  2. {
  3.    string text = "Yeah, you clicked the button!";
  4.    this.Button1.Click += delegate(object dlgSender, EventArgs dlgE)
  5.    {
  6.       Label1.Text = text;
  7.    };
  8. }


Anonymous methods may be used with more than one event or even in a completely different way. If you want to, you can reference the delegate in a variable and handle it as usual, as Listing 1-14 shows.


Listing 1-14: Using the Delegate As Usual

   
  1. void Page_Load (object sender, System.EventArgs e)
  2. {
  3.    EventHandler handler = delegate(object dlgSender, EventArgs dlgE)
  4.    {
  5.       Label1.Text = "Yeah, you clicked the button!";
  6.    };
  7.    this.Button1.Click += handler;
  8.    this.Button2.Click += handler;
  9. }

Internally, the C# compiler converts the anonymously implemented method into a class including a uniquely named method. The created delegate now points to this procedure. In real life, the usage of anonymous methods is particularly of interest with regard to smaller event-handling methods. For the sake of clarity, you should not overuse this method, particularly in combination with longer routines.

Another area you could apply such methods might be multithreading. Until now, an explicit method was required to start a new thread. In this particular case, the anonymous counterpart can provide even more clarity because the context becomes more obvious. In Listing 1-15, an approach based on a console application is exemplified. In this case, the dynamic method is directly passed in the constructor of the Thread class. This looks really funny, but it actually works!


Listing 1-15: The Entry Code for the Second Thread Passed As an Anonymous Method


    
  1. using System;
  2. using System.Threading;
  3. namespace MyLittleConsoleApp
  4. {
  5.    public class MainClass
  6.    {
  7.       [STAThread]
  8.       static void Main()
  9.       {
  10.          Thread myThread = new Thread(delegate()
  11.          {
  12.             for(int i = 0; i < 20; i++)
  13.             {
  14.                Console.WriteLine("Working thread ...");
  15.                Thread.Sleep(500);
  16.             }
  17.          });
  18.          myThread.Start();
  19.          for (int i = 0; i < 10; i++)
  20.          {
  21.             Console.WriteLine("In main.");
  22.             Thread.Sleep(1000);
  23.          }
  24.          Console.Read();
  25.        }
  26.    }
  27. }

转自:<<ASP.NET 2.0 Revealed>> Chapter 1
        What's New in C# 2.0?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值