博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
委托的多种写法
阅读量:7217 次
发布时间:2019-06-29

本文共 1751 字,大约阅读时间需要 5 分钟。

一、委托调用方式

1. 最原始版本:

    delegate string PlusStringHandle(string x, string y);

    class Program

    {

        static void Main(string[] args)

        {

            PlusStringHandle pHandle = new PlusStringHandle(plusString);

            Console.WriteLine(pHandle("abc", "edf"));

            Console.Read();

        }

         static string plusString(string x, string y)

        {

            return x + y;

        }

    }

 

 2. 原始匿名函数版:去掉“plusString”方法,改为

   PlusStringHandle pHandle = new PlusStringHandle(delegate(string x, string y)

   {

          return x + y;

    });

    Console.WriteLine(pHandle("abc", "edf"));

3. 使用LambdaC#3.0+),继续去掉“plusString”方法(以下代码均不再需要该方法)

     PlusStringHandle pHandle = (string x, string y) =>

      {

         return x + y;

      };

      Console.WriteLine(pHandle("abc", "edf"));

还有更甚的写法(省去参数类型)

      PlusStringHandle pHandle = (x, y) =>

      {

          return x + y;

       };

      Console.WriteLine(pHandle("abc", "edf"));

如果只有一个参数

   delegate void WriteStringHandle(string str);

   static void Main(string[] args)

   {

       //如果只有一个参数

       WriteStringHandle handle = p => Console.WriteLine(p);

       handle("lisi");

        Console.Read();

   }

  

二、委托声明方式

1. 原始声明方式见上述Demo

2. 直接使用.NET Framework定义好的泛型委托 Func Action ,从而省却每次都进行的委托声明。

  static void Main(string[] args)

  {

    WritePrint<int>(p => Console.WriteLine("{0}是一个整数", p), 10);

     Console.Read();

   }

  static void WritePrint<T>(Action<T> action, T t)

   {

      Console.WriteLine("类型为:{0},值为:{1}", t.GetType(), t);

      action(t);

    }

 

3. 再加上个扩展方法,就能搞成所谓的链式编程啦。

   class Program

   {  

      static void Main(string[] args)

      {

          string str = "所有童鞋:".plusString(p => p = p + " girl: lisi、lili\r\n").plusString(p => p + "boy: wangwu") ;

          Console.WriteLine(str);

          Console.Read();

       }

    }

   static class Extentions

    {

        public static string plusString<TParam>(this TParam source, Func<TParam, string> func)

        {

            Console.WriteLine("字符串相加前原值为:{0}。。。。。。", source);

            return func(source);

        }

    }

 看这个代码是不是和我们平时写的"list.Where(p => p.Age > 18)"很像呢?没错Where等方法就是使用类似的方式来实现的。

 

转载地址:http://sqtym.baihongyu.com/

你可能感兴趣的文章
如何设置启动SMTP、POP3以及IMAP4的SSL服务端口?
查看>>
自制函数strcpy
查看>>
gSoap开发(三)——WSDL简介
查看>>
软件RAID5项目实战!!!
查看>>
Java基础学习总结(21)——数组
查看>>
js格式化日期
查看>>
定时与延时任务
查看>>
Squid 日志分析 和反向代理
查看>>
Hadoop的安装及一些基本概念解释
查看>>
大容量分区命令parted
查看>>
从输入 URL 到页面加载完成的过程中都发生了什么事情?
查看>>
实例讲解JQuery中this和$(this)区别
查看>>
centos 7 静态ip地址模板
查看>>
影响系统性能的20个瓶颈
查看>>
shell的详细介绍和编程(上)
查看>>
软件开发性能优化经验总结
查看>>
面试题编程题05-python 有一个无序数组,如何获取第K 大的数,说下思路,实现后的时间复杂度?...
查看>>
kendo grid序号显示
查看>>
Spring 教程(二) 体系结构
查看>>
Indexes
查看>>