第七章 委托和事件

回调(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. Ubuntu16.04安装CDH5.14.2

    一.安装cloudera manager(下文简称cm) (一).环境及软件准备: 1.环境:Ubuntu16.04 desktop x 3 台 ip分别为:10.132.226.121,10.132 ...

  2. 嵌入式C语言自我修养 04:Linux 内核第一宏:container_of

    4.1 typeof 关键字 ANSI C 定义了 sizeof 关键字,用来获取一个变量或数据类型在内存中所占的存储字节数.GNU C 扩展了一个关键字 typeof,用来获取一个变量或表达式的类型 ...

  3. ACM1013:Digital Roots

    Problem Description The digital root of a positive integer is found by summing the digits of the int ...

  4. python2.7入门---2.x与3​​.x版本区别

        Python的3​​.0版本,常被称为Python 3000,或简称Py3k.相对于Python的早期版本,这是一个较大的升级.为了不带入过多的累赘,Python 3.0在设计的时候没有考虑向 ...

  5. 20155304田宜楠-第三次作业:虚拟机的安装与Linux学习

    安装VirtualBox虚拟机 安装VirtualBox虚拟机 这一步很简单,参考老师给的教程一步步安装,很快就完成了. 2.安装Ubuntu 这一步可是让我吃尽了苦头,我按照老师给的下载地址成功下载 ...

  6. 【CS】知识索引汇总

    Chapter 7 hello.o -> hello (链接) 一.静态链接 主要是将符号对应起来 两个主要任务:符号解析(符号引用与符号定义的对应).重定位(符号定义与内存位置的对应) 1. ...

  7. Ruby 配置vimrc

    https://ruby-china.org/topics/19315 mv ~/Downloads/vim-distinguished-develop/colors/*.vim ~/.vim/col ...

  8. [BZOJ4011][HNOI2015]落忆枫音-[dp乱搞+拓扑排序]

    Description 传送门 Solution 假如我们的图为DAG图,总方案数ans为每个点的入度In相乘(不算1号点).(等同于在每个点的入边选一条边,最后一定构成一棵树). 然而如果加了边x- ...

  9. [CF1042D] Petya and Array

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

  10. 【CF543E】Listening to Music

    [CF543E]Listening to Music 题面 洛谷 题目大意 给你一个长度为\(n\)序列\(a_i\),和一个常数\(m\),定义一个函数\(f(l,x)\)为\([l,l+m-1]\ ...