C# delegate & event

Posted on 2013-11-25 19:58  chayu3  阅读(234)  评论(0编辑  收藏  举报

public delegate void MyDelegate(string mydelegate);//声明一个delegate对象

//实现有相同参数和返回值的函数
        public void HelloDelegate(string mydelegate)
        {
            Console.WriteLine(mydelegate);
        }

 

 

MyDelegate mydelegate = new MyDelegate(testClass.HelloDelegate);//产生delegate对象
mydelegate("Hello delegate");//调用

From MSDN: [C# delegate的演进]

class Test
{
    delegate void TestDelegate(string s);
    static void M(string s)
    {
        Console.WriteLine(s);
    }

    static void Main(string[] args)
    {
        // Original delegate syntax required 
        // initialization with a named method.
        TestDelegate testDelA = new TestDelegate(M);

        // C# 2.0: A delegate can be initialized with
        // inline code, called an "anonymous method.匿名函式" This
        // method takes a string as an input parameter.
        TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

        // C# 3.0. A delegate can be initialized with
        // a lambda expression. The lambda also takes a string
        // as an input parameter (x). The type of x is inferred by the compiler.
        TestDelegate testDelC = (x) => { Console.WriteLine(x); };

        // Invoke the delegates.
        testDelA("Hello. My name is M and I write lines.");
        testDelB("That's nothing. I'm anonymous and ");
        testDelC("I'm a famous author.");

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    Hello. My name is M and I write lines.
    That's nothing. I'm anonymous and
    I'm a famous author.
    Press any key to exit.
 */

=====Declaring an event=====   
1, To declare an event inside a class, first a delegate type for the event must be declared, if none is already declared.
public delegate void ChangedEventHandler(object sender, EventArgs e);
2, Next, the event itself is declared.
public event ChangedEventHandler Changed;
3, Invoking an event
if (Changed != null)
Changed(this, e);
4, Hooking up to an event
  • Compose a new delegate onto that field.
// Add "ListChanged" to the Changed event on "List":
List.Changed += new ChangedEventHandler(ListChanged);
  • Remove a delegate from a (possibly composite) field.
// Detach the event and delete the list:
List.Changed -= new ChangedEventHandler(ListChanged);