首页 > Web开发 > 详细

NET委托和事件

时间:2016-03-26 23:30:16      阅读:244      评论:0      收藏:0      [点我收藏+]

1.委托的定义
委托的声明原型是
delegate<函数返回类型><委托名>(<函数参数>)
例子: public delegate void CheckDelegate(int number);//定义了一个委托
CheckDelegate,它可以注册返回void类型且有一个int作为参数的函数
这样就定义了一个委托,但是委托在.NET内相当于声明了一个类,类如果不实例化为对象,很多功能是没有办法使用的,
委托也是如此。
2.委托的实例化
委托实例化的原型是
<委托类型><实例化名>=new<委托类型>(<注册函数>)
例子: CheckDelegate _checkDelegate = CheckMod;//用函数CheckMod实例化上面的
CheckDelegate 委托为_checkDelegate
现在我们就可以像使用函数一样来使用委托了,在上面的例子中现在执行
_checkDelegate()就等同于执行CheckMod(),最关键的是现在函数CheckMod相当于放在了变量当中,
它可以传递给其它的CheckDelegate引用对象,而且可以作为函数参数传递到其他函数中,也可以作为函数的
返回类型。
2.用匿名函数初始化委托
匿名函数初始化委托的原型:
<委托类型> <实例化名> = new <委托类型>(delegate(<函数参数>){函数体});
也可以是<委托类型> <实例化名>=delegate(<函数参数>){函数体};
3.泛型委托
委托也支持泛型的使用
泛型委托原型:
delegate <T1> <委托名><T1,T2,T3...> (T1 t1,T2 t2,T3 t3...)
例子:
delegate T2 A<T1,T2>(T1 t);//定义有两个泛型(T1,T2)的委托,T2作为委托函数返回类型,T1作为委托函数参数类型

例1:

class Program
{
public delegate void Func1(int i);
public delegate int Func2(int i);
static void PrintNumber(int i)
{
Console.WriteLine(i);
}
static void Main(string[] args)
{
Func1 _func = new Func1(PrintNumber);
_func(5);
Console.ReadLine();
}

}

例2:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
delegate void Func1(int i);
delegate int Func2(int i);

static Func1 t1 = new Func1(delegate(int i)
{
Console.WriteLine(i);
});

static Func2 t2;

static void Main(string[] args)
{
t2 = delegate(int j)
{
return j;
};
t1(2);

Console.WriteLine(t2(1));

}
}
}

例3:

class Program
{
//泛型委托
public delegate T2 A<T1,T2>(T1 t);
static int test(int t){
return t;
}
static void Main(string[] args)
{
A<int,int> a = test;
Console.WriteLine(a(5));
Console.ReadKey();
}
}

NET委托和事件

原文:http://www.cnblogs.com/gylhaut/p/5324397.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!