Delegate比较全面的例子(需整理)
将Delegate理解为接口,只有一个方法的接口,这样最容易理解。这个方法只有声明,没有实现,实现在别的类。(实际上应该把它看作函数指针,不过接口更容易理解些。)
在你的类中有一个Delegate就相当于有一个接口。通过这个接口你可以调用一个方法,而这个方法在别的类定义,由别的类来干。
为了说的形象一点,举个例子:
学生考试完后成绩出来了,考的好了老师要表扬,考的不好了老师要批评。
使用接口的方法:
using System;
public class Student
{
private IAdviser adviser;
public void SetAdviser(IAdviser iadviser)
{
adviser = iadviser;
}
private int score;
public void SetScore(int value)
{
if (value > 100 || value < 0)
{
Console.Out.WriteLine("分数不对");
}
else
{
score = value;
if (adviser != null)
{
string result = adviser.Advise(score);
Console.Out.WriteLine("学生收到老师返回的结果\t"+result);
}
}
}
}
public interface IAdviser
{
string Advise(int score);
}
public class Teacher : IAdviser
{
public string Advise(int score)
{
if (score < 60)
{
Console.Out.WriteLine(score+"老师说加油");
return "不及格";
}
else
{
Console.Out.WriteLine(score+"老师说不错");
return "及格";
}
}
}
class MainClass
{
[STAThread]
private static void Main(string[] args)
{
IAdviser teacher = new Teacher();
Student s = new Student();
s.SetAdviser(teacher);
Console.Out.WriteLine("学生得到50分");
s.SetScore(50);
Console.Out.WriteLine("\n学生得到75分");
s.SetScore(75);
Console.ReadLine();
}
}
使用Delegate的方法:
using System;
using System.Threading;
public class Student
{
private int score;
public void SetScore(int value)
{
if (value > 100 || value < 0)
{
Console.Out.WriteLine("分数不对");
}
else
{
score = value;
if (AdviseDelegateInstance!= null)
{
string result=AdviseDelegateInstance(score);
Console.Out.WriteLine("学生收到老师返回的结果\t"+result);
}
}
}
public delegate string AdviseDelegate(int score);
public AdviseDelegate AdviseDelegateInstance;
}
public class Teacher
{
public string Advise(int score)
{
if(score<60)
{
Console.Out.WriteLine(score+"老师说加油");
return "不及格";
}
else
{
Console.Out.WriteLine(score+"老师说不错");
return "及格";
}
}
}
class MainClass
{
[STAThread]
static void Main(string[] args)
{
Teacher teacher=new Teacher();
Student s=new Student();
s.AdviseDelegateInstance=new Student.AdviseDelegate(teacher.Advise);
Console.Out.WriteLine("学生得到50分");
s.SetScore(50);
Console.Out.WriteLine("\n学生得到75分");
s.SetScore(75);
Console.ReadLine();
}
}
如果老师很忙不能及时回复怎么办?比如这样:
public class Teacher
{
public string Advise(int score)
{
Thread.Sleep(3000);
if(score<60)
{
Console.Out.WriteLine(score+"老师说加油");
return "不及格";
}
else
{
Console.Out.WriteLine(score+"老师说不错");
return "及格";
}
}
}
总不能让学生一直等下去吧,采用多线程并发的办法。
Interface的解决办法:
public void SetScore(int value)
{
if (value > 100 || value < 0)
{
Console.Out.WriteLine("分数不对");
}
else
{
score = value;
if (adviser != null)
{
Thread.adviserThread=new Thread(new ThreadStart(adviser.Advise()));
adviserThread.Start();
}
}
}
但是它不能使用带参数的函数,怎么办?(谁知道方法请指教)
.Net2.0提供了新的方法ParameterizedThreadStart
用Delegate解决(异步调用):
public void SetScore(int value)
{
if (value > 100 || value < 0)
{
Console.Out.WriteLine("分数不对");
}
else
{
score = value;
if (AdviseDelegateInstance!= null)
{
AdviseDelegateInstance.BeginInvoke(score,null,null);
}
}
}
不过这样我们失去了老师的返回结果,不知道有没有及格了。
采用轮讯的方法去获得结果:
public void SetScore(int value)
{
if (value > 100 || value < 0)
{
Console.Out.WriteLine("分数不对");
}
else
{
score = value;
if (AdviseDelegateInstance!= null)
{
IAsyncResult res = AdviseDelegateInstance.BeginInvoke(score,null, null);
while( !res.IsCompleted ) System.Threading.Thread.Sleep(1);
string result = AdviseDelegateInstance.EndInvoke(res);
Console.Out.WriteLine("学生收到老师返回的结果\t"+result);
}
}
}
不过这样主线程又被阻塞了,采用回调的方式: (注:接口也可以采用回调的方式获得返回值)
public void SetScore(int value)
{
if (value > 100 || value < 0)
{
Console.Out.WriteLine("分数不对");
}
else
{
score = value;
if (AdviseDelegateInstance!= null)
{
IAsyncResult res = AdviseDelegateInstance.BeginInvoke(score, newSystem.AsyncCallback(CallBackMethod), null);
}
}
}
private void CallBackMethod(IAsyncResult asyncResult)
{
string result = AdviseDelegateInstance.EndInvoke(asyncResult);
Console.Out.WriteLine("学生收到老师返回的结果\t" + result);
}
这样就比较得到了一个比较好的解决方案了。我们再来看看BeginInvoke的第四个参数是干吗的呢?
public void SetScore(int value)
{
if (value > 100 || value < 0)
{
Console.Out.WriteLine("分数不对");
}
else
{
score = value;
if (AdviseDelegateInstance!= null)
{
AdviseDelegateInstance.BeginInvoke(score, new System.AsyncCallback(CallBackMethod), "idior");
}
}
}
private void CallBackMethod(IAsyncResult asyncResult)
{
string result = AdviseDelegateInstance.EndInvoke(asyncResult);
string stateObj=(string)asyncResult.AsyncState;
Console.Out.WriteLine("学生{0}收到老师返回的结果\t" + result,stateObj.ToString());
}
哦,原来它可以用来标记调用者的一些信息。(这里采取的是硬编码的方式,你可以把它改为学生的id之类的信息)。
总结:Delegate类似与Interface但是功能更加强大和灵活,它甚至还可以绑定到Static方法只要函数签名一致,而且由于+=操作符的功能,实现多播也是极为方便(即Observer模式),在此不再举例。
(补充:多播的时候改一下SetScore函数)
public void SetScore(int value)
{
if (value > 100 || value < 0)
{
Console.Out.WriteLine("分数不对");
}
else
{
score = value;
if (AdviseDelegateInstance!= null)
{
foreach( AdviseDelegate ad in AdviseDelegateInstance.GetInvocationList())
{
ad.BeginInvoke(score, new System.AsyncCallback(CallBackMethod), "idior");
}
}
}
}
本文没什么新的内容,就是自己练一下手,写个总结材料,希望对大家有帮助。.net2.0提供了更好的线程模型。
完整源代码如下:
using System;
using System.Threading;
public class Student
{
private int score;
public void SetScore(int value)
{
if (value > 100 || value < 0)
{
Console.Out.WriteLine("分数不对");
}
else
{
score = value;
if (AdviseDelegateInstance!= null)
{
AdviseDelegateInstance.BeginInvoke(score, new System.AsyncCallback(CallBackMethod), "idior");
}
}
}
private void CallBackMethod(IAsyncResult asyncResult)
{
string result = AdviseDelegateInstance.EndInvoke(asyncResult);
string stateObj=(string)asyncResult.AsyncState;
Console.Out.WriteLine("学生{0}收到老师返回的结果\t" + result,stateObj);
}
public delegate string AdviseDelegate(int score);
public AdviseDelegate AdviseDelegateInstance;
}
public class Teacher
{
public string Advise(int score)
{
Thread.Sleep(3000);
if (score < 60)
{
Console.Out.WriteLine(score + "老师说加油");
return "不及格";
}
else
{
Console.Out.WriteLine(score + "老师说不错");
return "及格";
}
}
}
class MainClass
{
[STAThread]
private static void Main(string[] args)
{
Teacher teacher = new Teacher();
Student s = new Student();
s.AdviseDelegateInstance= new Student.AdviseDelegate(teacher.Advise);
Console.Out.WriteLine("学生得到50分");
s.SetScore(50);
Console.Out.WriteLine("\n学生得到75分");
s.SetScore(75);
Console.ReadLine();
}
}
参考资料: .NET Delegates: A C# Bedtime Story
Delegate比较全面的例子(需整理)的更多相关文章
- SQL Server 存储过程 (需整理)
Transact-SQL中的存储过程,非常类似于Java语言中的方法,它可以重复调用.当存储过程执行一次后,可以将语句缓存中,这样下次执行的时候直接使用缓存中的语句.这样就可以提高存储过程的性能. Ø ...
- C#窗体控件简介ListBox(需整理)
ListBox 控件 ListBox 控件又称列表框,它显示一个项目列表供用户选择.在列表框中,用户 一次可以选择一项,也可以选择多项. 1.常用属性: (1) Items属性: 用于存放列表框中的列 ...
- Java 常用类的使用例子(整理)
可变字符序列——StringBuffer StringBuffer类和String类的方法几乎一样,不过StringBuffer对象表示的字符串是可以改变的,而String对象保存的字符串是不可变的. ...
- IntelliJ Idea 常用快捷键列表 (需整理下) https://blog.csdn.net/dc_726/article/details/42784275
[常规] https://blog.csdn.net/dc_726/article/details/42784275https://jingyan.baidu.com/article/59a015e3 ...
- [UE4] C++实现Delegate Event实例(例子、example、sample)
转自:http://aigo.iteye.com/blog/2301010 虽然官方doc上说Event的Binding方式跟Multi-Cast用法完全一样,Multi-Cast论坛上也有很多例子, ...
- jQuery 2.0.3 源码分析 事件绑定 - bind/live/delegate/on
事件(Event)是JavaScript应用跳动的心脏,通过使用JavaScript ,你可以监听特定事件的发生,并规定让某些事件发生以对这些事件做出响应 事件的基础就不重复讲解了,本来是定位源码分析 ...
- 转载: jQuery事件委托( bind() \ live() \ delegate()) [委托 和 绑定的故事]
转载:http://blog.csdn.net/zc2087/article/details/7287429 随着DOM结构的复杂化和Ajax等动态脚本技术的运用,事件委托自然浮出了水面.jQuery ...
- JDK动态代理例子
JDK动态代理的代理类必须实现于接口.如果要代理类,则使用CGLIB代理. 先定义一个接口: public interface Character { public void show(); } 接着 ...
- 事件委托live,delegate,on区别
事件委托 我们知道,DOM在为页面中的每个元素分派事件时,相应的元素一般都在事件冒泡阶段处理事件.在类似 body > div > a 这样的结构中,如果单击a元素,click事件会从a一 ...
随机推荐
- MySQL Crash Course #18# Chapter 26. Managing Transaction Processing
InnoDB 支持 transaction ,MyISAM 不支持. 索引: Changing the Default Commit Behavior SAVEPOINT 与 ROLLBACK TO ...
- python集合set{ }、集合函数及集合的交、差、并
通过大括号括起来,用逗号分隔元素,特点 1.由不同元素组成,如果定义时存在相同元素,处理时会自动去重 2.无序 3.元素只能是不可变类型,即数字.字符串.布尔和元组,但集合本身可变 4.可直接定义集合 ...
- troubleshooting-When importing query results in parallel, you must specify --split-by.
原因分析 -m 4 \ 导数命令中map task number=4,当-m 设置的值大于1时,split-by必须设置字段(需要是 int 类型的字段),如果不是 int类型的字段,则需要加上参数- ...
- Linux系统对IO端口和IO内存的管理
引用:http://blog.csdn.net/ce123_zhouwei/article/details/7204458 一.I/O端口 端口(port)是接口电路中能被CPU直接访问的寄存器的地址 ...
- Python3基础 str lstrip 去掉字符串左边的空格
Python : 3.7.0 OS : Ubuntu 18.04.1 LTS IDE : PyCharm 2018.2.4 Conda ...
- User-Defined Table Types 用户自定义表类型
Location 数据库--可编程性--类型--用户定义表类型 select one database--> programmability-->types-->user--defi ...
- 伪类:after的使用以及结合attr来添加属性的技巧
本案例以实现侧边栏的效果为例来说明 直接上代码看效果: css <style type="text/css"> *{;;list-style: none;} ul{;t ...
- Python Sip [RuntimeError: the sip module implements API v11.0 to v11.2 but the PyQt5.QtCore module requires API v11.3]
不知道原因,尝试卸载.编译安装均失败.只有这样曲线救国 import matplotlib matplotlib.use("WXAgg",warn=True) import mat ...
- React Native 之 定义的组件 (跨文件使用)
哈哈的~~~今天介绍的是自定义组件 然后去使用这个组件,让这个组件传递这各种文件之间 哈哈 下面开始吧!!!! 我们所要创建的是一个自定义的Button,先创建一个js文件起名为MyButton, ...
- github+hexo搭建博客
引言 之前用阿里云弹性web托管采用wordpress搭建的个人博客,经过我使用一段时间之后发现存在很多问题: 网站的响应速度非常慢,估计打开主页需要3-4s的时间,我经过搜索发现很多人都有这 ...