您的位置:首页 > 其它

.Net的委托和事件的直接理解

2007-04-06 12:49 435 查看
初学者在理解委托和事件时常常被msdn搞糊涂,为了让初学.net的人快速应用.net的委托和事件模型编程,我在这里主要是提出理解的关键,以下代码都可直接运行,先看下面的代码。

using System;

namespace delegeteTest
{

class delegeteClass
{

public delegate void fHandler(int a); //关键-此行可以看成类的声明
public fHandler f0;
public void d(int a,int b )
{
int c=a+b;
f0(c);
}
}
class test
{
public void output(int mun)
{
System.Console .WriteLine ("{0}",mun);
}

[stathread]
static void Main(string[] args)
{
test t=new test ();
delegeteClass dc=new delegeteClass ();
dc.f0 =new delegeteTest.delegeteClass.fHandler (t.output);//实例的初始化
dc.d(2,3);
}
}
}

解释一下"关键": 实际上 public delegate void fHandler(int a);可以看成如下:

class fHandler
{.....}

类内部由编译器自动完成,是一个sealed类通过反汇编可以看到,是一个类的声明,它检查加入自己的函数的信息,如,返回值和参数类型

现在熟悉vc++的人可能感觉到public delegate void fHandler(int a);这句就象一个宏

现在好了既然是个类的定义,那么也可以直接拿到命名空间下了

using System;

namespace delegeteTest
{
public delegate void fHandler(int a);//fHandler现在上升到了类的层次

class delegeteClass
{
public fHandler f0;//声明了委托fHandler的实例f0;

public fHandler f1;//也可以再声明一个fHandler类的实例f1;
public void d(int a,int b )
{
int c=a+b;
f0(c);
}
}
class test
{
public void output(int mun)
{
System.Console .WriteLine ("{0}",mun);
}

[stathread]
static void Main(string[] args)
{
test t=new test ();
delegeteClass dc=new delegeteClass ();
dc.f0 =new delegeteTest.fHandler (t.output);//此行做相应的修改
dc.d(2,3);
}
}
}

有以上可知public delegate void fHandler(int a)这行代码只能放在能够声明类的地方,自然fHandler.后面的函数都是静态方法了,如fHandler.Equals (...);

那么fhandler到底声明了什么? 实际上是声明了函数的类型,既函数的有关信息(如返回值,参数类型)。说到委托还是要说一下委托类型的实例。在msdn中的很多地方,(委托)这个词指的是委托类型的实例,它拥有了一个列表,列表的每一项包含了函数信息和函数所在的对象的引用。

在声明fhandler类的实例f0的时候,f0还不能用,是空的,所以f0需要初始化 dc.f0 =new delegeteTest.fHandler (t.output); 初始化的参数包含了两个信息 t--对象的引用,output--函数信息,如果把初始化的这句注释掉,你运行一下看有什么信息----“未将对象引用设置到对象的实例”。另外output函数的参数和返回值需要和fHandler的类声明一致,这是由编译器在编译时检查的。

经过初始化之后 现在实例中有了一项数据(实际上大多数只有一项,这样效率比较高,也就是single cast的,此时实例是Delegate类型的(注意是大写的D))。

现在说一下委托的多播(multi cast),实际上委托的多播就是把列表里的每一项函数调用一次),但是多播的效率不是很高的所以委托的大部分实例都是单播(single cast),另外可能委托的实例会根据列表内函数的个数来运行不同的机制(这里我们就没必要研究它了)。看下面的代码:

namespace delegeteTest
{
public delegate void fHandler(int a);

class delegeteClass
{
public fHandler f0;
public fHandler f1;
public void d(int a,int b )
{
int c=a+b;
f1(c); //合并指针列表的多播委托
}
}
class test
{
public void output(int mun)
{
System.Console .WriteLine (" 函数1显示{0}",mun);
}
public void output1(int mun)
{
System.Console .WriteLine (" 函数2显示{0}",mun);
}

[stathread]
static void Main(string[] args)
{
test t=new test ();
delegeteClass dc=new delegeteClass ();
dc.f0 =new delegeteTest.fHandler (t.output);
dc.f1 =new fHandler (t.output1 );

system.console .WriteLine ("第一次触发");
dc.d (2,3);//第一次触发

dc.f1 =(fHandler)Delegate.Combine (dc.f0 ,dc.f1 );//合并生成新的]函数列表
dc.f1 =(fHandler)MulticastDelegate.Combine (dc.f1 ,dc.f0 );//同上
System.Console .WriteLine ("第二次触发");
dc.d(2,3);//第二次触发
}
}
}
实际上dc.f1 =(fHandler)MulticastDelegate.Combine (dc.f1 ,dc.f0 );和dc.f1 =(fHandler)Delegate.Combine (dc.f1 ,dc.f0 );效果是一样的;由上面的例子可知我们完全可以由delegate 来构造我们自己的事件。微软为了方便大家进行编程,为我们提供了event。
using System;

namespace delegeteTest
{
public delegate void fHandler(int a);

class delegeteClass
{
public fHandler f0;
public fHandler f1;
public event fHandler f3; //关键--实际上此行也可以看成一个宏

public void d(int a,int b )
{
int c=a+b;
f3(c); // 改由event进行
}
}
class test
{
public void output(int mun)
{
System.Console .WriteLine (" 第1显示{0}",mun);
}
public void output1(int mun)
{
System.Console .WriteLine (" 第2显示{0}",mun);
}

[stathread]
static void Main(string[] args)
{
test t=new test ();
delegeteClass dc=new delegeteClass ();
dc.f0 =new delegeteTest.fHandler (t.output);
dc.f1 =new fHandler (t.output1 );

dc.f3 +=new fHandler(t.output); //f3是event
System.Console .WriteLine ("第一次触发");
dc.d (2,3);//第一次触发

system.console .WriteLine ("第二次触发");
dc.f3 +=(fHandler)Delegate.Combine (dc.f0 ,dc.f1 );//添加列表到f3
dc.d(2,3);//第二次触发
}
}
}

通过ildasm反汇编可以看到public event fHandler f3宏声明了两个成员

.field private class delegeteTest.fHandler f3和对f3的一个包装:

.event delegeteTest.fHandler f3
{
.addon instance void delegeteTest.delegeteClass::add_f3(class delegeteTest.fHandler)
.removeon instance void delegeteTest.delegeteClass::remove_f3(class delegeteTest.fHandler)
},

所以上面红色的代码可以替换成如下:

private fHandler _f3;//由于不能与属性名相同,所以用_f3,是私有
public event fHandler f3
{
add
{
this._f3 += value;
}
remove
{
this._f3 -= value;
}

}

event 关键字方便了大家的习惯,同时它(由event定义的事件)在类的外部使用时隐藏了它的成员函数(这一点非常重要,几乎就是使用event关键字的原因),并且只能用“+=”和“-=”来操作,除此之外和直接声明public fHandler f3没有区别。它可以和上面的f0,f1一样允许有各种参数和返回值。是在委托基础上的。实际上我们都能用delegate 来构造我们想要的事件,这就是delegate 在.net里的地位很高的原因。

下面我就说说一般控件的事件模型

我先谈一下控件里的"on事件名"这个函数 如:OnTextChange(EventArgs e),类似的有很多,实际上这是一种编程方面的习惯,他代表的是引发这个TextChanged事件(注意不是代表TextChanged(e)的函数),具体的说就是在Text变量已经被赋值后执行的一个函数OnTextChanged(),OnTextChanged里面包含了类似TextChanged(e)这样的引发事件的代码。如果你重写了OnTextChanged(),而没有在(重写的函数)里添加base.OnTextChanged(e);那么你在外部添加的TextChanged事件的处理程序,永远也不会触发到,也就是TextChanged事件失效了。

下面我就写了一个重写ontextchanged()的例子,是关于只能输入数字的textbox, 里面有输入整数部分的数量限制属性 MaxOfInt 和小数限制属性MaxOfLittle,还有decimal 类型的值 ValueDecimal属性,还有一个DecmalValueChanged事件,由于重写了OnTextChanged事件而没有在里面写base.TextChanged (e);所以你们如果再使用TextChanged事件就一点效果都没有了。

下面的控件不怕粘贴,不怕汉字

using System;
using System.ComponentModel;
using System.ComponentModel .Design ;

namespace contr
{
/// <summary>
///
/// </summary>
public class TextBoxNum : System.Windows.Forms.TextBox
{
public delegate void ValueChangedHandler(object o,decimal DecValue);
private ValueChangedHandler ValueChanged;//声明了一个实例
public int MaxInt=8;
public int MaxLittle=2;
public decimal DecimalValue=0;
public TextBoxNum()
{

//
// TODO: 在此处添加构造函数逻辑
//
}
private void InitializeComponent()
{
}
protected override void OnTextChanged(EventArgs e)
{
if(this.Text .Length !=0&&(this.Text[0])=='.')
{
this.Text ="0.";
this.SelectionStart=(this.Text .Length );
return;
}
string s=this.Text.Trim ();
if(this.MaxLittle ==0)
{
if(s.IndexOf ('.')>0||this.Text .Length >this.MaxInt )
{
this.Text =this.ValueDecimal .ToString ();
this.SelectionStart=(this.Text .Length );
return;

}
}

if(s ==""){return;}
int j=s .IndexOf ('.');
if((j<0&&s.Length >this.MaxInt ))
{

this.text =this.ValueDecimal .ToString ();
this.SelectionStart=(this.Text .Length );
return;
}
if(j>-1&&(s.Length -j-1)>this.MaxLittle)
{
this.Text =this.ValueDecimal .ToString ();
this.SelectionStart=(this.Text .Length );
return;
}
int a=0;

char[] temp=s.ToCharArray () ;
for(int i=0;i<s.Length ;i++)
{
if(Char.IsDigit(temp[i]))
{
continue;
}
else if(temp[i]=='.')
{
a++;
if(a>1)
{
this.Text =this.ValueDecimal .ToString ();
this.SelectionStart=(this.Text .Length );
return;
}

continue;
}
this.Text =this.ValueDecimal .ToString ();
this.SelectionStart=(this.Text .Length );
return;

}
this.ValueDecimal =decimal.Parse (this.Text);
base.TextChanged (e);

}

public event ValueChangedHandler DecmalValueChanged
{
add
{
this.ValueChanged += value;
}
remove
{
this.ValueChanged -= value;
}
}
public decimal ValueDecimal
{
get
{
return this.DecimalValue ;
}
set
{
this.DecimalValue =value;
if(ValueChanged!=null)
{
ValueChanged(this,this.DecimalValue );
}

}
}
[Browsable(true),DefaultValue(8)]
public int MaxOfInt
{
get
{
return this.MaxInt ;
}
set
{
if(value<=29)
{
this.MaxInt =value;
this.MaxLength =this.MaxLittle +value +1;
}
else
{
this.MaxInt =29;
this.MaxLength =this.MaxLittle +29 +1;
}
}
}
[Browsable(true),DefaultValue(2)]
public int MaxOfLittle
{
get
{
return this.MaxLittle ;
}
set
{
if(value<=29)
{
this.MaxLittle =value;
this.MaxLength =value +this.MaxInt +1;
}
else
{
this.MaxLittle =29;
this.MaxLength =29 +this.MaxInt +1;

}
}

}
}
}

以上只是帮助大家理解,因为这样才能事半功倍,尤其上面的关键,可以省了大家不少力气。希望专家批评指正
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: