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
  • 相关阅读:
    PHP递归方法实现前序、中序、后序遍历二叉树
    php循环方法实现先序、中序、后序遍历二叉树
    Mac charles 抓取https请求,安装证书后还是显示unknown
    PHP工厂模式
    PHP策略模式2
    PHP单例模式
    PHP 面试知识点整理归纳
    十大迷你iPhone天气应用
    来自极客标签10款最新设计素材-系列十三
    帮助快速生成页面固定显示元素的jQuery插件
  • 原文地址:https://www.cnblogs.com/imstrive/p/6073211.html
Copyright © 2011-2022 走看看