第七章 委托和事件

回调(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. PTA基础编程题目集6-3简单求和 (函数题)

    6-3 简单求和 (10 分) 本题要求实现一个函数,求给定的N个整数的和. 函数接口定义: int Sum(int List[],int N) 其中给定整数存放在数组List[]中,正整数N是数组元 ...

  2. 使用VS2015 编译 64位的boost库

    别人写的编译参考: 目标:使用VS2015 编译 64位的boost库. 一直以来都是在Win32环境下Build和使用boost,但现在基本上每天都在64位Win7下工作,所以很有必要把这几天的经验 ...

  3. stm32 IO口八种模式区别

    初学STM32,遇到I/O口八种模式的介绍,网上查了一下资料,下面简明写出这几种模式的区别,有不对的地方请大家多多指正! 上拉输入模式:区别在于没有输入信号的时候默认输入高电平(因为有弱上拉).下拉输 ...

  4. 138. Subarray Sum【Lintcode,by java】

    Description Given an integer array, find a subarray where the sum of numbers is zero. Your code shou ...

  5. 20155321 2016-2017-2 《Java程序设计》第十周学习总结

    20155321 2016-2017-2 <Java程序设计>第十周学习总结 教材学习内容总结 网络概览 局域网和广域网:局域网通常限定在一个有效的地理区域之内,广域网由许多局域网组成.最 ...

  6. Kali linux更新源

    1.更新软件源: 修改sources.list文件: leafpad /etc/apt/sources.list 然后选择添加以下适合自己较快的源(可自由选择,不一定要全部): #官方源deb htt ...

  7. loj2538 「PKUWC 2018」Slay the Spire

    pkusc 快到了--做点题涨涨 rp. ref我好菜啊QAQ. 可以发现期望只是一个幌子.我们的目的是:对于所有随机的选择方法(一共 \(\binom{2n}{m}\)种),这些选择方法都最优地打出 ...

  8. elasticsearch备份与恢复

    备注:以下代码在kibana插件下运行: # 创建一个备份用的仓库# type:fs文件系统# 支持Shared filesystem, Amazon S3, HDFS和Azure #Cloud# l ...

  9. 【BUG】12小时制和24小时制获取当天零点问题

    [BUG]12小时制和24小时制获取当天零点问题 最近在写定时服务的时候,要获取当天的零点这个时间,但是是这样获取的 DateTime dt = DateTime.Parse(DateTime.Now ...

  10. Debian 给非 ROOT 用户添加 sudoer 权限

    问题描述 从官方镜像安装的 Debian 9 (Stretch)比较纯净,但因此需要自己安装.配置许多常用的 Linux 应用,这里就需要 sudo (super user do)临时获取 root ...