1. 委托

From: http://www.cnblogs.com/daxnet/archive/2008/11/08/1687014.html

类是对象的抽象,而委托则可以看成是函数的抽象。一个委托代表了具有相同参数列表和返回值的所有函数。

  1. class Program
  2. {
  3. delegate int CalculateDelegate(int a, int b);
  4. int add(int a, int b)
  5. {
  6. return a + b;
  7. }
  8. static void Main(string[] args)
  9. {
  10. CalculateDelegate d = new Program().add;
  11. //CalculateDelegate d = new CalculateDelegate(new Program().add);
  12. Console.WriteLine(d(1, 2));
  13. Console.ReadKey();
  14. }
  15. }
    class Program
{
delegate int CalculateDelegate(int a, int b); int add(int a, int b)
{
return a + b;
} static void Main(string[] args)
{
CalculateDelegate d = new Program().add;
//CalculateDelegate d = new CalculateDelegate(new Program().add);
Console.WriteLine(d(1, 2));
Console.ReadKey();
}
}

委托作为参数,在C#中非常常见。比如线程的创建,需要给一个ThreadStart或者ParameterizedThreadStart委托作为参数,而在线程执行的时候,将这个参数所指代的函数用作线程执行体。再比如:List<T>类型的Find方法的参数也是一个委托,它把“怎么去查找”或者说“怎么样才算找到”这个问题留给了开发人员。这有点像模板模式。

委托作为返回值一般会用在“根据不同情况决定使用不同的委托”这样的情形下。这有点像工厂模式。

2. 异步调用

From: http://www.cnblogs.com/daxnet/archive/2008/11/10/1687013.html

异步通过委托来完成。.net使用delegate来"自动"生成的异步调用是使用了另外的线程(而且是线程池线程)。

  1. class Program
  2. {
  3. static TimeSpan Boil()
  4. {
  5. DateTime begin = DateTime.Now;
  6. Console.WriteLine("水壶:开始烧水...");
  7. Thread.Sleep(6000);
  8. Console.WriteLine("水壶:水已经烧开了!");
  9. return DateTime.Now - begin;
  10. }
  11. delegate TimeSpan BoilingDelegate();
  12. static void Main(string[] args)
  13. {
  14. Console.WriteLine("小文:将水壶放在炉子上");
  15. BoilingDelegate d = new BoilingDelegate(Boil);
  16. IAsyncResult result = d.BeginInvoke(BoilingFinishedCallback, null);
  17. Console.WriteLine("小文:开始整理家务...");
  18. for (int i = 0; i < 20; i++)
  19. {
  20. Console.WriteLine("小文:整理第{0}项家务...", i + 1);
  21. Thread.Sleep(1000);
  22. }
  23. }
  24. static void BoilingFinishedCallback(IAsyncResult result)
  25. {
  26. AsyncResult asyncResult = (AsyncResult)result;
  27. BoilingDelegate del = (BoilingDelegate)asyncResult.AsyncDelegate;
  28. Console.WriteLine("(烧水一共用去{0}时间)", del.EndInvoke(result));
  29. Console.WriteLine("小文:将热水灌到热水瓶");
  30. Console.WriteLine("小文:继续整理家务");
  31. }
  32. }
class Program
{
static TimeSpan Boil()
{
DateTime begin = DateTime.Now;
Console.WriteLine("水壶:开始烧水...");
Thread.Sleep(6000);
Console.WriteLine("水壶:水已经烧开了!");
return DateTime.Now - begin;
}
delegate TimeSpan BoilingDelegate(); static void Main(string[] args)
{
Console.WriteLine("小文:将水壶放在炉子上");
BoilingDelegate d = new BoilingDelegate(Boil);
IAsyncResult result = d.BeginInvoke(BoilingFinishedCallback, null);
Console.WriteLine("小文:开始整理家务...");
for (int i = 0; i < 20; i++)
{
Console.WriteLine("小文:整理第{0}项家务...", i + 1);
Thread.Sleep(1000);
}
} static void BoilingFinishedCallback(IAsyncResult result)
{
AsyncResult asyncResult = (AsyncResult)result;
BoilingDelegate del = (BoilingDelegate)asyncResult.AsyncDelegate;
Console.WriteLine("(烧水一共用去{0}时间)", del.EndInvoke(result));
Console.WriteLine("小文:将热水灌到热水瓶");
Console.WriteLine("小文:继续整理家务");
}
}

EndInvoke会使得调用线程阻塞,直到异步函数处理完成。EndInvoke会使得调用线程阻塞,直到异步函数处理完成。EndInvoke会使得调用线程阻塞,直到异步函数处理完成。EndInvoke会使得调用线程阻塞,直到异步函数处理完成。EndInvoke调用的返回值也就是异步处理函数的返回值。

3. 泛型委托

[Serializable]

publicdelegatevoid EventHandler<TEventArgs>(object sender, TEventArgs e) where TEventArgs: EventArgs;

  1. class IntEventArgs : System.EventArgs
  2. {
  3. public int IntValue { get; set; }
  4. public IntEventArgs() { }
  5. public IntEventArgs(int value)
  6. { this.IntValue = value; }
  7. }
  8. class StringEventArgs : System.EventArgs
  9. {
  10. public string StringValue { get; set; }
  11. public StringEventArgs() { }
  12. public StringEventArgs(string value)
  13. { this.StringValue = value; }
  14. }
  15. class Program
  16. {
  17. static void PrintInt(object sender, IntEventArgs e)
  18. {
  19. Console.WriteLine(e.IntValue);
  20. }
  21. static void PrintString(object sender, StringEventArgs e)
  22. {
  23. Console.WriteLine(e.StringValue);
  24. }
  25. static void Main(string[] args)
  26. {
  27. EventHandler<IntEventArgs> ihandler =
  28. new EventHandler<IntEventArgs>(PrintInt);
  29. EventHandler<StringEventArgs> shandler =
  30. new EventHandler<StringEventArgs>(PrintString);
  31. ihandler(null, new IntEventArgs(100));
  32. shandler(null, new StringEventArgs("Hello World"));
  33. }
  34. }
class IntEventArgs : System.EventArgs
{
public int IntValue { get; set; }
public IntEventArgs() { }
public IntEventArgs(int value)
{ this.IntValue = value; }
} class StringEventArgs : System.EventArgs
{
public string StringValue { get; set; }
public StringEventArgs() { }
public StringEventArgs(string value)
{ this.StringValue = value; }
} class Program
{
static void PrintInt(object sender, IntEventArgs e)
{
Console.WriteLine(e.IntValue);
} static void PrintString(object sender, StringEventArgs e)
{
Console.WriteLine(e.StringValue);
} static void Main(string[] args)
{
EventHandler<IntEventArgs> ihandler =
new EventHandler<IntEventArgs>(PrintInt);
EventHandler<StringEventArgs> shandler =
new EventHandler<StringEventArgs>(PrintString); ihandler(null, new IntEventArgs(100));
shandler(null, new StringEventArgs("Hello World"));
}
}

4. 匿名方法

http://www.cnblogs.com/daxnet/archive/2008/11/12/1687011.html

只需要给出方法的参数列表(甚至也可以不给)以及方法具体实现,而不需要关心方法的返回值,更不必给方法起名字。最关键的是,只在需要的地方定义匿名方法,保证了代码的简洁。比如用于委托作为函数参数。

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. List<string> names = new List<string>();
  6. names.Add("Sunny Chen");
  7. names.Add("Kitty Wang");
  8. names.Add("Sunny Crystal");
  9. List<string> found = names.FindAll(
  10. delegate(string name)
  11. {
  12. return name.StartsWith("sunny",
  13. StringComparison.OrdinalIgnoreCase);
  14. });
  15. if (found != null)
  16. {
  17. foreach (string str in found)
  18. Console.WriteLine(str);
  19. }
  20. }
  21. }
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
names.Add("Sunny Chen");
names.Add("Kitty Wang");
names.Add("Sunny Crystal"); List<string> found = names.FindAll(
delegate(string name)
{
return name.StartsWith("sunny",
StringComparison.OrdinalIgnoreCase);
}); if (found != null)
{
foreach (string str in found)
Console.WriteLine(str);
}
}
}

5. Lambda表达式

http://www.cnblogs.com/daxnet/archive/2008/11/14/1687010.html

从委托的角度来看,Lambda表达式与匿名方法没有区别。Lambda表达式的定义方式为:“([参数列表]) => 表达式”。

  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. List<string> names = new List<string>();
  6. names.Add("Sunny Chen");
  7. names.Add("Kitty Wang");
  8. names.Add("Sunny Crystal");
  9. List<string> found = names.FindAll
  10. (
  11. // Lambda Expression Implementation
  12. name => name.StartsWith(
  13. "sunny",
  14. StringComparison.OrdinalIgnoreCase)
  15. );
  16. if (found != null)
  17. {
  18. foreach (string str in found)
  19. Console.WriteLine(str);
  20. }
  21. }
  22. }
class Program
{
static void Main(string[] args)
{
List<string> names = new List<string>();
names.Add("Sunny Chen");
names.Add("Kitty Wang");
names.Add("Sunny Crystal"); List<string> found = names.FindAll
(
// Lambda Expression Implementation
name => name.StartsWith(
"sunny",
StringComparison.OrdinalIgnoreCase)
); if (found != null)
{
foreach (string str in found)
Console.WriteLine(str);
}
}
}

6. 事件

http://www.cnblogs.com/daxnet/archive/2008/11/21/1687008.html

事件由委托定义。事件的触发方只需要确定好事件处理函数的签名即可。也就是说,触发方只需要定义在事件发生时需要传递的参数,而在订阅方,只需要根据这个签名定义一个处理函数,然后将该函数“绑定”到事件列表,就可以通过签名中的参数,对事件做相应的处理。

委托-异步调用-泛型委托-匿名方法-Lambda表达式-事件【转】的更多相关文章

  1. C# delegate event func action 匿名方法 lambda表达式

    delegate event action func 匿名方法 lambda表达式 delegate类似c++的函数指针,但是是类型安全的,可以指向多个函数, public delegate void ...

  2. 18、(番外)匿名方法+lambda表达式

    概念了解: 1.什么是匿名委托(匿名方法的简单介绍.为什么要用匿名方法) 2.匿名方法的[拉姆达表达式]方法定义 3.匿名方法的调用(匿名方法的参数传递.使用过程中需要注意什么) 什么是匿名方法? 匿 ...

  3. 委托delegate 泛型委托action<> 返回值泛型委托Func<> 匿名方法 lambda表达式 的理解

    1.使用简单委托 namespace 简单委托 { class Program { //委托方法签名 delegate void MyBookDel(int a); //定义委托 static MyB ...

  4. C#多线程+委托+匿名方法+Lambda表达式

    线程 下面是百度写的: 定义英文:Thread每个正在系统上运行的程序都是一个进程.每个进程包含一到多个线程.进程也可能是整个程序或者是部分程序的动态执行.线程是一组指令的集合,或者是程序的特殊段,它 ...

  5. C#委托总结-匿名方法&Lambda表达式

    1,匿名方法 匿名方法可以在声明委托变量时初始化表达式,语法如下 之前写过这么一段代码: delegate void MyDel(string value); class Program { void ...

  6. (28)C#委托,匿名函数,lambda表达式,事件

    一.委托 委托是一种用于封装命名和匿名方法的引用类型. 把方法当参数,传给另一个方法(这么说好理解,但实际上方法不能当参数,传入的是委托类型),委托是一种引用类型,委托里包含很多方法的引用 创建的方法 ...

  7. 匿名函数 =匿名方法+ lambda 表达式

    匿名函数的定义和用途 匿名函数是一个"内联"语句或表达式,可在需要委托类型的任何地方使用. 可以使用匿名函数来初始化命名委托[无需取名字的委托],或传递命名委托(而不是命名委托类型 ...

  8. 泛型委托及委托中所涉及到匿名方法、Lambda表达式

    泛型委托及委托中所涉及到匿名方法.Lambda表达式 引言: 最初学习c#时,感觉委托.事件这块很难,其中在学习的过程中还写了一篇学习笔记:委托.事件学习笔记.今天重新温故委托.事件,并且把最近学习到 ...

  9. 委托+内置委托方法+多播委托+lambda表达式+事件

    委托概念:如果我们要把方法当做参数来传递的话,就要用到委托.简单来说委托是一个类型,这个类型可以赋值一个方法的引用. 声明委托: 在C#中使用一个类分两个阶段,首选定义这个类,告诉编译器这个类由什么字 ...

随机推荐

  1. 【C++基础之十四】函参的缺省

    可能会有这么一个函数,在大部分的情况下,我们不用给它传递参数,但在某些特殊情况下,我们需要给它传递参数,那怎么办呢? 简单啊,写两个一样的方法,一个带参,一个不带参... 这样也太没水准了.来点高端的 ...

  2. LaTex 下编译后不能显示中文,或者中文乱码

    在 Sublime Text 中编辑以下文件并保存(第一行的注释很重要),按下 Cammand + B 编译: %!TEX program = xelatex \documentclass[UTF8] ...

  3. iOS加密个人见解

    说说常用的加密方式 1.单向加密,譬如 md5 .SHA 但是这种单向加密安全性也不高了,现在cpu.gpu都那么强大,运算速度很快,彩虹表 撞库 还是容易被攻破的. 如果非得用的话,可以md5加盐, ...

  4. 《Qt编程的艺术》——5.1 手动布局

    在传统的GUI设计中,每个控件(Widget)都要手动地绑定在窗口之上的一个点上(也就是说,这个控件被指定成了给定GUI元素的父对象),同时还要指定这个控件的高度和宽度.作为所有图形元素的基础类,QW ...

  5. java File的getLastModified在不同操作系统以下存在差异

    java对文件读取改动时间(getLastModified())在不同的操作系统下存在差异  //1.在windows下,返回值是毫秒级别,不存在问题 //2.在Linux下,返回的值是毫秒值,可是会 ...

  6. MPreview.js

    Word,PPT 文档预览组件(图片预览组件) 移动端请移步 MPreview.mobile Demo参考 http://demo.webjyh.com/MPreview/ 特此说明 此插件是我在项目 ...

  7. C# 封装-属性

    属性使封装更容易 可以使用属性(properties),这些方法对其他对象来说就像是字段,可以用属性来获取或设置一个后备字段,后备字段就是由属性所设置的一个字段名 private int number ...

  8. 搭建高可用mongodb集群—— 分片

    从节点每个上面的数据都是对数据库全量拷贝,从节点压力会不会过大? 数据压力大到机器支撑不了的时候能否做到自动扩展? 在系统早期,数据量还小的时候不会引起太大的问题,但是随着数据量持续增多,后续迟早会出 ...

  9. ExtJS4.x动态加载js文件

    动态加载js文件是ext4.x的一个新特性,可以有效的减少浏览器的压力,提高渲染速度.如动态加载自定义组件 1.在js/extjs/ux目录下,建立自定义组件的js文件. 2.编写MyWindow.j ...

  10. 终极解法According to TLD or attribute directive in tag file, attribute select does not accept any expressions

    3天硬是是把这个问题解决了 有时候突然上个厕所灵感就来了 第一次向用JSTL解析xml 然后我想遍历整个xml文档打印出来 居然不让我输入变量 那让我怎么办啊 在网上各种找答案 说什么<%@ t ...