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
  • 相关阅读:
    重视个人成长 远离心灵鸡汤——由一则“心灵鸡汤”想到的
    vim 学习
    针对不同包之间的action跳转,怎么配置?
    Bootstrap 栅格系统
    struts2的s:iterator 标签 详解
    struts2 <s:property/>标签的使用--输出时间格式转换
    Myeclipse中把java代码导成UML类图
    大学毕业后坚持学习有什么用
    【BZOJ2754】喵星球上的点名(AC自动机)
    Codeforces Round #466 (Div. 2)
  • 原文地址:https://www.cnblogs.com/imstrive/p/6073211.html
Copyright © 2011-2022 走看看