第七章 委托和事件

回调(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. Windos10 mysql-8.0.13安装手顺

    一.下载 1.1 官方下载地址:https://dev.mysql.com/downloads/mysql/ ,点击Download 1.2 点击 No thanks,just start my do ...

  2. 【Mac】解决「另一个活跃的 Homebrew 进程正在进行中」问题

    问题描述 在安装 tesseract 的语言包时,由于网络下载速度太慢,我按下 ctrl + z 退出了安装,当再次输入安装命令时,系统报错如下: 解决方法 使用以下命令删除 homebrew 进程锁 ...

  3. 论 Python Opencv 中文路径及中文文件名图像文件读取的两种方式

    python 2中对于中文字符的处理可谓是诟病已久,虽然python 3 使用统一编码解决了中文字符串的问题,但在使用opencv中imread函数读取中文路径图像文件时仍会报错. 1) 借助nump ...

  4. ruby学习笔记(1)-puts,p,print的区别

    ruby学习笔记-puts,p,print的区别 共同点:都是用来屏幕输出的. 不同点:puts 输出内容后,会自动换行(如果内容参数为空,则仅输出一个换行符号):另外如果内容参数中有转义符,输出时将 ...

  5. WPF 背景颜色渐变的滑动条实现

    原文:WPF 背景颜色渐变的滑动条实现 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/BYH371256/article/details/83507 ...

  6. Dlib库中实现正脸人脸检测的测试代码

    Dlib库中提供了正脸人脸检测的接口,这里参考dlib/examples/face_detection_ex.cpp中的代码,通过调用Dlib中的接口,实现正脸人脸检测的测试代码,测试代码如下: #i ...

  7. Nginx入门篇(三)之虚拟主机配置

    一.虚拟主机概念 所谓虚拟主机,在Web服务当中就是一个独立的网站站点,这个站点对应独立的域名(也有可能是IP或者端口),具有独立的程序和资源目录,可以独立地对外提供服务供用户访问. 这个独立的站点在 ...

  8. 解决 mysql in 查询排序问题

    select id,title from za_item where -- id ,) 返回的结果第一条是对应id是1000,第二条是1003. 如果我们想让结果和in里面的排序一致,可以这么做. s ...

  9. php引用&使用笔记

    引用与赋值是两个概念:引用是共用同一个内存地址,一个改变其他也会变,赋值是另外开辟内存空间,一个改变其他不会变 一个简单例子: $a=123; //$a开辟一个内存空间存储123 $b=&$a ...

  10. 生成dataset的几种方式

    1.常用的方式通过sparksession读取外部文件或者数据生成dataset(这里就不讲了)  注: 生成Row对象的方法提一下:RowFactory.create(x,y,z),取Row中的数据 ...