第七章 委托和事件

回调(callback)函数是Windows编程的一个重要方面,实际上是方法调用的指针,也称为函数指针。

.Net以委托的形式实现了函数指针的概念,.Net的委托是类型安全的。

  1. 委托

使用委托的时候,需要先声明,后实例化。

声明委托

delegate void MethodInvoker();

可以在委托前加public,private,protected。

 

实际上,定义委托是指定义一个新类,委托实现为派生自基类System.MulticastDelegate。

 

使用委托

private delegate string GetAString();

 

static void Main()

{

    int x = 10;

    GetAString firstMethod = new GetAString(x.ToString);

    Console.WriteLine("String is {0}", firstMethod());

    // Console.WriteLine("String is {0}", firstMethod.Invoke());

 

 

}

委托在语法上总是带有一个参数的构造函数,这个参数就是委托引用的方法

C#引入和委托推断:

GetAString firstMethod = x.ToString;

 

多播委托

包含多个方法调用的委托。调用委托的个数也与方法相同

delegate void DoubleOp(double value);

 

DoubleOp operations = MathOperations.MultiplyByTwo;

operations += MathOperations.Square;

operations(2.0);

会执行两个函数

也可使用-=

多播委托包含一个逐个调用的委托集合。如果通过委托调用的一个方法抛出了异常,整个迭代就会停止。解决方法:

DemoDelegate d1 = One;

d1 += Two;

 

Delegate[] delegates = d1.GetInvocationList();

foreach(DemoDelegate d in delegates)

{

    try

    {

    }

    catch(Exception)

    {

    }

}

 

匿名方法

delegate string DelegateTest(string val);

…

DelegateTest an1 = delegate(string param)

{

    statements;

};

 

lambada表达式

C#3.0引入,创建匿名函数

DelegateTest an1 = param =>

{

    statements;

    return "some string";

};

lambada表达式中,运算符=>左边列出了参数类型和个数

可以忽略类型,只写标识符,用括号括住,当标识符只有一个时,可以省略括号。

 

  1. 事件

例子

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Timers;

 

namespace Chapter_7

{

public delegate void MessageHandler(string messageText);

 

public class Connection

{

public event MessageHandler MessageArrived;

private Timer pollTimer;

private static Random random = new Random();

private uint count = 0;

 

public Connection()

{

pollTimer = new Timer(100);

pollTimer.Elapsed += new ElapsedEventHandler(CheckForMessage);

}

 

public void Connect()

{

pollTimer.Start();

}

 

public void Disconnect()

{

pollTimer.Stop();

}

 

private void CheckForMessage(object source, ElapsedEventArgs e)

{

Console.WriteLine("Checking for new message.");

if ((random.Next(9) == 0) && (MessageArrived != null))

{

count++;

MessageArrived("Hello Mum!");

}

}

}

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace Chapter_7

{

public class Display

{

public void DisplayMessage(string message)

{

Console.WriteLine("message arrived:{0}", message);

}

}

}

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace Chapter_7

{

public delegate void DoubleOp(double value);

class Program

{

static void Main(string[] args)

{

 

Connection myConnection = new Connection();

Display myDisplay = new Display();

myConnection.MessageArrived += new MessageHandler(myDisplay.DisplayMessage);

myConnection.Connect();

Console.ReadKey();

}

}

}

第一行定义事件发布器

第二行定义事件订阅器

最后一行演示事件使用方法

参考:http://www.runoob.com/csharp/csharp-event.html

C#高级编程 (第六版) 学习 第七章:委托和事件的更多相关文章

  1. C#高级编程 (第六版) 学习 第五章:数组

    第五章 数组 1,简单数组 声明:int[] myArray; 初始化:myArray = new int[4]; 为数组分配内存. 还可以用如下的方法: int[] myArray = new in ...

  2. C#高级编程 (第六版) 学习 第四章:继承

    第四章 继承 1,继承的类型 实现继承: 一个类派生于一个基类型,拥有该基类型所有成员字段和函数. 接口继承 一个类型只继承了函数的签名,没有继承任何实现代码.   2,实现继承 class MyDe ...

  3. C#高级编程 (第六版) 学习 第三章:对象和类型

    第三章 对象和类型 1,类和结构 类存储在托管堆上 结构存储在堆栈上   2,类成员 类中的数据和函数称为类成员 数据成员 数据成员包括了字段.常量和事件   函数成员 方法:与某个类相关的函数,可以 ...

  4. C#高级编程 (第六版) 学习 第六章:运算符和类型强制转换

    第六章 运算符和类型强制转换 1,运算符 类别 运算符 算术运算符 + - * / % 逻辑运算符 & | ^ ~ && || ! 字符串连接运算符 + 增量和减量运算符 ++ ...

  5. C#高级编程 (第六版) 学习 第一章:.Net体系结构

    第一章 .Net体系结构 1,公共语言运行库(Common Language Runtime, CLR) .Net Framework的核心是其运行库的执行环境,称为公共语言运行库,或.Net运行库. ...

  6. C#高级编程(第六版)学习:第三十一章:Windows窗体

    第三十一章 Windows窗体 创建Windows窗体应用程序 在文本编辑器中输入: /* * form.cs * a simple windows form * */ using System; u ...

  7. C#高级编程 (第六版) 学习 第二章:C#基础

    第二章 基础 1,helloworld示例: helloworld.cs using System; using System.Collections.Generic; using System.Li ...

  8. ASP.NET MVC 4高级编程(第4版)

    <ASP.NET MVC 4高级编程(第4版)> 基本信息 作者: (美)Jon Galloway    Phil Haack    Brad Wilson    K. Scott All ...

  9. 《UNIX环境高级编程(第3版)》

    <UNIX环境高级编程(第3版)> 基本信息 原书名:Advanced Programming in the UNIX Environment (3rd Edition) (Addison ...

随机推荐

  1. Elasticsearch 6.3.1、Head插件 安装及配置

    安装Elasticsearch Elasticsearch下载地址:https://www.elastic.co/cn/downloads/elasticsearch 也可以直接使用wget下载到某目 ...

  2. python学习笔记(一)学习资料记录

    相关资料网站 1. python3简明教程 适合新学者,因为可以在线操作,并且校验结果,同时还有考试系统.比较基础 2. python数据分析数据科学中文英文工具书籍下载 免费的中英文数据的PDF下载 ...

  3. 20155317 实验二 Java面向对象程序设计

    20155317 实验二 Java面向对象程序设计 实验内容 初步掌握单元测试和TDD 理解并掌握面向对象三要素:封装.继承.多态 初步掌握UML建模 熟悉S.O.L.I.D原则 了解设计模式 实验步 ...

  4. 使用WinIO库实现保护模式下的IO和内存读写

    问题已解决: 原因是函数的调用方式与WinIO中不一致,使用的时候漏掉了__stdcall. 函数原定义为: 在实际的GPIO读写中遇到以下问题: SetPortVal可正常写入,但是GetPortV ...

  5. MySQL 安装 + Windows7

    Window版本 1.下载 http://dev.mysql.com/downloads/mysql/ 2.解压 如果想要让MySQL安装在指定目录,那么就将解压后的文件夹移动到指定目录,如:D:\m ...

  6. [CF1042D] Petya and Array

    题面 题解 这道题目到底叫什么好呢?? 史上最短CDQ分治题 记一个前缀和,然后CDQ分治即可. 代码 #include<cstdio> #include<algorithm> ...

  7. 【LG4309】【BZOJ3173】[TJOI2013]最长上升子序列

    [LG4309][BZOJ3173][TJOI2013]最长上升子序列 题面 洛谷 BZOJ 题解 插入操作显然用平衡树就行了 然后因为后面的插入对前面的操作无影响 就直接在插入完的序列上用树状数组求 ...

  8. Nginx入门篇(六)之反向代理和负载均衡

    一.Nginx负载均衡集群 介绍 负载均衡(Load Balance)集群提供了一种行之有效的办法,来扩展网络设备和服务器负载.带宽和吞吐量,同时加强了网络数据处理能力,提供了网络的灵活性和可用性. ...

  9. Android开发笔记——视频录制播放常见问题

    本文分享自己在视频录制播放过程中遇到的一些问题,主要包括: 视频录制流程 视频预览及SurfaceHolder 视频清晰度及文件大小 视频文件旋转 一.视频录制流程 以微信为例,其录制触发为按下(住) ...

  10. hdu2065"红色病毒"问题(指数母函数+快速幂取模)

    "红色病毒"问题 Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Other ...