Delegates, Events, and Lambda Expressions

The C# event Keyword

As a shortcut, so you don’t have to build custom methods to add or remove methods to a delegate’s invocation list, C# provides the event keyword.

作为捷径,你不用必须建立自定义方法来从委托的 invocation list的添加和移除函数,C#提供了event这个关键字。

When the compiler processes the event keyword, you are automatically provided with registration and unregistration methods, as well as any necessary member variables for your delegate types.

当编译器处理event这个关键字,你被自动的提供注册和解除注册的方法和一些必要的成员变量为你的委托类型。

10-05 Understanding C# Events

理解C#事件

Delegates are fairly interesting constructs(柯1)(建造,构筑) in that they enable objects in memory to engage in a two-way conversation. 

委托是相当有趣的结构,这种结构能够使内存中的对象进行双向通信。

   public class Car
   {
        public delegate void CarEngineHandler(string msgForCaller);
        // Now a public member!
        public CarEngineHandler listOfHandlers;
        // Just fire out the Exploded notification. 
        public void Accelerate(int delta)
        {
            if (listOfHandlers != null)
                listOfHandlers("Sorry, this car is dead...");
        }
  }
 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("***** Agh! No Encapsulation! *****\n");
            // Make a Car.
            Car myCar = new Car();
            // We have direct access to the delegate!
            myCar.listOfHandlers = new Car.CarEngineHandler(CallWhenExploded);
            myCar.Accelerate(10);
            // We can now assign to a whole new object...
            // confusing at best.
            myCar.listOfHandlers = new Car.CarEngineHandler(CallHereToo);
            myCar.Accelerate(10);
            // The caller can also directly invoke the delegate! 
            myCar.listOfHandlers.Invoke("hee, hee, hee...");
            Console.ReadLine();
        }

        static void CallWhenExploded(string msg) 
        { 
            Console.WriteLine(msg); 
        }

        static void CallHereToo(string msg) 
        { 
            Console.WriteLine(msg); 
        }
}

 

Exposing public delegate members breaks encapsulation, which not only can lead to code that is hard to maintain (and debug), but could also open your application to possible security risks!

暴露公共委托成员破坏了封装性,造成了不但导致代码很难去维护(调试),并且使你的程序可能的安全风险。

10-05-01 The C# event Keyword

As a shortcut, so you don’t have to build custom methods to add or remove methods to a delegate’s invocation list, C# provides the event keyword. When the compiler processes the event keyword, you are automatically provided with registration and unregistration methods, as well as any necessary member variables for your delegate types. 

posted @ 2015-02-05 00:14  海川0  阅读(112)  评论(0编辑  收藏  举报