码迷,mamicode.com
首页 > Windows程序 > 详细

C# 委托与事件

时间:2015-04-03 11:30:32      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:delegate   c#   实例   namespace   

委托

委托建立的是一条方法链条,可以让一个对象依次执行链条上的方法。可以简化代码,提高效率。

声明

public delegate int Delegate(int i);//声明委托

对委托注册方法

匹配规则:
方法额返回类型必须和委托的返回类型相同。
方法的参数必须和委托的方法参数相同,参数名称可以不同。
public void F1(int i,int j);//no
public int F2(int i);//no
public int F3(int m,int n);//yes

实例化委托

委托是一个类,所以需要实例化。
namespace Test
{
delegate int Delegate(int i);
class Program
{
public int F1(int i)
{
return i;
}
static void Main(string[] args)
{
Program p=new Program();
Delegate d1=new Delegate(p.F1);//创建实例


}
}
}



委托的方法列表

将多个方法绑定到同一个委托变量。,当调用委托变量时,可以一次调用所有绑定的方法。
namespace Test
{
delegate int Delegate(int i);
class Program<pre name="code" class="csharp">namespace Test
{
public delegate int Delegate(int i);
public class Program
{
public static int F1(int i)
{
return i;
}
public int F2(int j)
{
return j;
}
static void Main(string[] args)
{
Program p=new Program();
Delegate d1=new Delegate(p.F1);
Delegate d2=new Delegate(p.F2);
Delegate d3=d1+d2;//给委托注册方法
int i3=d3(10);
}
}
}


调用委托

委托是一个方法链条,调用委托也就是调用了委托实例包含的所有方法。
namespace Test
{
public delegate void Delegate(int i);
public class Program
{
public static void F1(int i)
{
Console.WriteLine(i.ToString());
}
public static void F2(int i)
{
Cosnole.WriteLine(i.ToString());
}
static void Main(string[[] args)
{

Delegate d1=new Delegate(Program.F1);
Delegate d2=new Delegate(Program.F2);
Delegate d3=d1+d2;
d1(10);//调用d1实例
d2(200);//调用d2实例
d3(201);//调用d3实例
}
}
}


事件

事件是一种特殊的委托

声明事件的委托

public delegate void EventHandler(object sender,EventArgs e);

声明事件本身

public event EventHandler Print;//申明事件Print


注册事件&移除事件

namespace Test
{
public delegate void EventHandler(object sender,EventArgs e)
class Program
{
public event EventHandler Print;
public void F1(object sender,EventArgs e)
{
Console.WriteLine("F1");
}
public void F2(object sender,EventArgs e)
{
Console.WriteLine("F2");
}
static void Main(string[] args)
{
Program p=new Program();
p.Print+=new EventHandler(p.F1);//给事件注册一个方法
p.Print+=new EventHandler(p.F2);
if(p.Print!=null)
{
p.Print(null,null);
}
Console.Writeline();
p.Print-=new EventHandler(p.F1);//从事件中移除方法F1;
if(p.Print!=null)
{
p.Print(null,null);
}
Console.ReadLine();
}
}
}

调用事件

namespace Test
{
public delegate void EventHandler(object sender,EventArgs e);
class Program
{
public event EventHandler Print;
public void F1(object sender,eventargs e)
{
Console.WriteLine("F1");
}
static void Main(string[] args)
{
Program p=new Program();
p.Print+=new EventHandler(p.F1);
if(p.Print!=null)
{
p.Print(null,null);//调用事件
}
Console.ReadLine();
}
}
}



C# 委托与事件

标签:delegate   c#   实例   namespace   

原文地址:http://blog.csdn.net/u013470102/article/details/44850535

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!