一直以为C#的接口中不能定义事件呢, 因为我们知道接口中不能定义变量.
(现在才发现Event并不是定义变量, 而是定义了两个方法, 其IL如下:)
Code
//interface MyInterface
//{
// event Mydelegate ddd;
// void Fire();
//}
.class interface private abstract auto ansi Crash.MyInterface
{
.method public hidebysig newslot specialname abstract virtual
instance void add_ddd(class Crash.Mydelegate 'value') cil managed synchronized
{
} // end of method MyInterface::add_ddd
.method public hidebysig newslot specialname abstract virtual
instance void remove_ddd(class Crash.Mydelegate 'value') cil managed synchronized
{
} // end of method MyInterface::remove_ddd
.method public hidebysig newslot abstract virtual
instance void Fire() cil managed
{
} // end of method MyInterface::Fire
.event Crash.Mydelegate ddd
{
.addon instance void Crash.MyInterface::add_ddd(class Crash.Mydelegate)
.removeon instance void Crash.MyInterface::remove_ddd(class Crash.Mydelegate)
} // end of event MyInterface::ddd
} // end of class Crash.MyInterface
可以看到, 我们定义的事件ddd, 被展开成了两个函数add_ddd和remove_ddd, 而且是抽象的, 需要我们在子类中实现.
那如何在子类中实现这个两个函数呢? 如下:
class my : MyInterface
{
public event Mydelegate ddd;
public void Fire()
{
ddd.BeginInvoke(10, null, null);
}
}
注意: 我们定义自己的Delegate时, 其实编译器把它展开为了一个类, IL如下:
Code
//delegate void Mydelegate(int dd);
.class private auto ansi sealed Crash.Mydelegate
extends [mscorlib]System.MulticastDelegate
{
.method public hidebysig specialname rtspecialname
instance void .ctor(object 'object',
native int 'method') runtime managed
{
} // end of method Mydelegate::.ctor
.method public hidebysig newslot virtual
instance void Invoke(int32 dd) runtime managed
{
} // end of method Mydelegate::Invoke
.method public hidebysig newslot virtual
instance class [mscorlib]System.IAsyncResult
BeginInvoke(int32 dd,
class [mscorlib]System.AsyncCallback callback,
object 'object') runtime managed
{
} // end of method Mydelegate::BeginInvoke
.method public hidebysig newslot virtual
instance void EndInvoke(class [mscorlib]System.IAsyncResult result) runtime managed
{
} // end of method Mydelegate::EndInvoke
} // end of class Crash.Mydelegate