zoukankan      html  css  js  c++  java
  • 委托与事件(三)

    除了使用delegate关键字定义委托,还可以使用系统关键字Action、Func和Predicate直接使用委托

    Action(无返回值):

    (1)使用匿名方法调用委托:

    1     /****************使用匿名方法**************/
    2     Action<string> action = delegate(string str)
    3     {
    4         Console.WriteLine(str);
    5     };
    6     action("Parameters");

    (2)使用Lambda表达式调用委托:

    1     /****************使用Lambda表达式**************/
    2     Action<string> action = (string str) =>
    3     {
    4         Console.WriteLine(str);
    5     };
    6     action("Parameters");

    (3)调用无参方法:

    • 方法体:
    1     private static void ShowMsg()
    2     {
    3         Console.WriteLine("Action无参无返回!");
    4     }
    • 通过Action调用方法:
    1     Action action = ShowMsg;
    2     action();

    (4)调用带参数的方法:

    • 方法体:
    1     private static void ShowMsg(string msg)
    2     {
    3         Console.WriteLine("Action单参无返回!参数为:{0}", msg);
    4     }
    • 通过Action调用方法:
    1     /****************使用带参数方法**************/
    2     Action<string> action = new Action<string>(ShowMsg);
    3     action("测试");

    Func(有返回值)

    (1)使用匿名方法调用委托:

    1     Func<string> func = delegate()
    2     {
    3         return "测试Func";
    4     };
    5     string strReturn = func();
    6     Console.WriteLine(strReturn);
    7     //输出
    8     //--> 测试Func

    (2)使用Lambda表达式调用委托:

    1     Func<string> func = ()=>
    2     {
    3         return "测试Func";
    4     };
    5     string strReturn = func();
    6     Console.WriteLine(strReturn);
    7     //输出:
    8     //-->测试Func

    (3)调用无参方法

    • 方法体:
    1     private static string GetString()
    2     {
    3         return "测试Func";
    4     }
    • 通过Func调用方法:
    1     Func<string> func = GetString;
    2     string str = func();
    3     Console.WriteLine(str);
    4     //输出
    5     //-->测试Func

    (4)调用单参方法:

    • 方法体:
    1     private static string GetUpperString(string str)
    2     {
    3         return str.ToUpper();
    4     }
    • 通过Func调用方法
    1     Func<string, string> func = GetUpperString;
    2     string strReturn = func("test");
    3     Console.WriteLine(strReturn);
    4     //输出:
    5     //-->TEST

    Predicate(单参返回bool类型)

    • 方法体:
    1     private static bool IsLarger(int number)
    2     {
    3         if (number > 100)
    4             return true;
    5         else
    6             return false;
    7     }
    • 通过Predicate调用方法:
    1     Predicate<int> predicate = IsLarger;
    2     bool status = predicate(100);
    3     Console.WriteLine(status);
    4     //输出:
    5     //-->False
  • 相关阅读:
    深入解析MySQL分区(Partition)功能
    使用mysqlreplicate命令快速搭建 Mysql 主从复制
    MySQL优化/面试,看这一篇就够了
    Nginx+Keepalived高可用集群
    高并发核心技术
    Redis详解
    memcached 常用命令及使用说明
    MemCached详解
    音频和视频
    frameset 和iframe框架标签
  • 原文地址:https://www.cnblogs.com/imstrive/p/6073211.html
Copyright © 2011-2022 走看看