delegate(代理,委托)

下面的例子描述了delegate的声明,初始化和调用:

public partial class Form1 : Form

{

// declares a delegate, it has one parameter.

delegate void help(string message);

public Form1()

{

InitializeComponent();

// anonymous method.

this.MouseClick += delegate(object sender, MouseEventArgs e)

{

MessageBox.Show("hello world");

};

}

private void Form1_Load(object sender, EventArgs e)

{

// 2 ways to initialize the delegate

// 1.decides what to do with this delegate, here using a named method "ShowMessage".

help h1 = new help(Form1.ShowMessage);   // also we can write it as "help h1 = Form1.ShowMessage", they are the same meaning.

// 2.decides what to do with this delegate, here using a anonymous method.

help h2 = delegate(string message) { MessageBox.Show(message); };

// 2 ways to call the delegate

// 1.call the delegate

h1.Invoke("message from delegate1");

// 2.call the delegate

h2("message from delegate2");

}

private static void ShowMessage(string message)

{

MessageBox.Show(message);

}

}
接下来总结一下常用的事件的注册方法,这里我列出了四种方式:

Code

注册这些事件如下:

Code

下面介绍三个常用的delegate:Func,Action和Predicate

1. Func<T,TResult> delegate:

语法:public delegate TResult Func<T, TResult>(T arg);

用它封装一个方法,该方法只有一个参数,T是参数的类型,TResult是返回值的类型。

例如:

Code

 

2. Action<T>, Action<T1, T2>,Action 等等
 它封装一个方法,带有一个或多个参数,但是没有返回值。

 它与Func的区别就是Func有返回值,Action无返回值。

3. Predicate<T>

predicate的意思是断定为,预言成..., 它封装了一个方法,带有一个参数,返回值是bool型。

你可能感兴趣的:(delegate)