zoukankan      html  css  js  c++  java
  • c# Action,Func,Predicate委托

    System命名空间下已经预先定义好了三中泛型委托,Action,Func和Predicate,这样我们在编程的时候,就不必要自己去定义这些委托了

    Action是没有返回值的

    Func是带返回值的

    不同的.netframework版本下,能定义的参数个数可能不同

    Predicate,只有一个参数,返回值是bool型

     /// <summary>
            /// Action泛型委托:.netframework4下 可以有0到16个参数
            /// </summary>
            public void TestAction()
            {
                Action a1 = () => Console.WriteLine("嘿嘿");//Lambda表达式
                a1();
    
                Action<string> a2 = s => Console.WriteLine("你好," + s);
                a2("阿牛");
    
                Action<int, int> a3 = delegate(int a, int b) {//匿名方法
                    Console.WriteLine("a+b=" + (a + b));
                };
                a3(4, 5);
            }
    
    
            /// <summary>
            /// Func泛型委托:
            /// </summary>
            public void TestFunc()
            {
                Func<string> func1 = () => "你好";//表达式Lambda
                Console.WriteLine(func1());
    
                Func<string, string> func2 = s => { return "你好" + s; };//语句Lambda
                Console.WriteLine(func2("阿牛"));
    
                Func<int, int, int> func3 = delegate(int a, int b)//匿名方法
                {
                    return a + b;
                };
                Console.WriteLine(func3(4, 5));
            }
    
            /// <summary>
            /// Predicate泛型委托
            /// </summary>
            public void TestPredicate()
            {
                Predicate<int> pre1 = a => a == 2;
                if (pre1(3))
                {
                    Console.WriteLine("3==2");
                }
                else
                {
                    Console.WriteLine("3<>2");
                }
    
                List<string> list = new List<string>();
                list.Add("A1");
                list.Add("A2");
                list.Add("B1");
    
                List<string> list2 = list.FindAll(s => s.StartsWith("B"));
                List<string> list3 = list.FindAll(delegate(string s) {
                    return s.StartsWith("B");
                });
            }
  • 相关阅读:
    Rancher安装
    JDK8日期时间对象
    String经典面试题
    String
    单例模式
    多线程
    接口
    代码块
    内存吞金兽(Elasticsearch)的那些事儿 -- 常见问题痛点及解决方案
    内存吞金兽(Elasticsearch)的那些事儿 -- 写入&检索原理
  • 原文地址:https://www.cnblogs.com/niuge/p/3666621.html
Copyright © 2011-2022 走看看