使用C 深入研究.NET委托和事件

2008-02-23 05:24:53来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

 简介

  类型安全机制的实现原来采用的是C风格的回调(callback)函数,而.NET Framework引入了委托和事件来替代原来的方式;他们被广泛地使用。我们在这里尝试使用标准C 来实现和之类似的功能,这样我们不但能够对这些概念有一个更好的认识,而且同时还能够体验C 的一些有趣的技术。

  C#中的委托和事件关键字

  首先我们来看一个简单的C#程式(下面的代码略有删节)。执行程式的输出结果如下显示:

SimpleDelegateFunction called from Ob1,

string=Event fired!

Event fired!(Ob1): 3:49:46 PM on

Friday, May 10, 2002

Event fired!(Ob1): 1056318417

SimpleDelegateFunction called from Ob2,

string=Event fired!

Event fired!(Ob2): 3:49:46 PM on

Friday, May 10, 2002

Event fired!(Ob2): 1056318417

  任何这些都源于这样一行代码:dae.FirePrintString("Event fired!");

  在利用C 来实现这些功能时,我模仿了C#的语法并完全按照功能的需要进行研发。

namespace DelegatesAndEvents
{
class DelegatesAndEvents
{
public delegate void PrintString(string s);
public event PrintString MyPrintString;
public void FirePrintString(string s)
{
if (MyPrintString != null)MyPrintString(s);
}
}

class TestDelegatesAndEvents
{
[STAThread]
static void Main(string[] args)
{
DelegatesAndEvents dae =new DelegatesAndEvents();
MyDelegates d = new MyDelegates();
d.Name = "Ob1";
dae.MyPrintString =new DelegatesAndEvents.PrintString(d.SimpleDelegateFunction);
// ... more code similar to the
// above few lines ...
dae.FirePrintString("Event fired!");
}
}
class MyDelegates
{
// ... "Name" property omitted...
public void SimpleDelegateFunction(string s)
{
Console.WriteLine("SimpleDelegateFunction called from {0}, string={1}", m_name, s);
}
// ... more methods ...
}
}



[1] [2] [3] [4] [5] 下一页

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇: C 中指针的使用艺术

下一篇: C 研发常用工具“群英会”

热门词条
热门标签