zoukankan      html  css  js  c++  java
  • Delegate Action<T in> Func<T in,out Tresult> Predicate<T>

    action<T> 和  func<T> 都是delegate的简写形式,其中T为可以接受的参数类型

    action<T> 指那些只有输入参数,没有返回值

    Delegate 的代码

    1 public delegate void myDelegate(string str);  //申明
    2 public static void HellowChinese(string strChinese)  
    3 {  
    4     Console.WriteLine("Good morning," + strChinese);  
    5     Console.ReadLine();  
    6 }  
    7   
    8 myDelegate d = new myDelegate(HellowChinese);  
    9 d("Mr wang"); 
    用了Action之后:
    1 public static void HellowChinese(string strChinese)  
    2 {  
    3     Console.WriteLine("Good morning," + strChinese);  
    4     Console.ReadLine();  
    5 }  
    6   
    7 Action<string> action = HellowChinese;  
    8 action("Spring.");  
     1 public class MyBlogBase
     2     {    
     3         public string myName;
     4         Action<string> myAction;    
     5         public MyBlogBase()
     6         {
     7             //myAction = delegate(string curName) { myName = curName; };//采用匿名委托
     8             //myAction = new Action<string>(SetAction); //指定一个实际的方法
     9             myAction = curname => { myName = curname; }; //使用Lamda表达式
    10            
    11         }
    12         private void SetAction(string name)
    13         {
    14             myName = name;
    15         }
    16     }

    在上例中,给出了3种使用Action的方法,方法一:采用匿名委托,方法二:指定一个实际的方法。方法三:使用Lamda表达式。

    相当于省去了定义委托的步骤

    func<T in,T Tresult> 这个和上面的那个是一样的,区别是这个有返回值Tresult

    1 public static string HelloEnglish(string strEnglish)  
    2 {  
    3     return "Hello." + strEnglish;  
    4 }  
    5   
    6 Func<string, string> f = HelloEnglish;  
    7 Console.WriteLine(f("Srping ji"));  
    8 Console.ReadLine();  

    Predicate<T>:也是一种委托,表示定义一组条件并确定指定对象是否符合这些条件的方法.此方法常在集合的查找中被用到,如:数组,正则拼配的结果集中被用到。使用此方法快捷方便,使用代码如下:

     1 Predicate<int> myPredicate;
     2         int[] myNum = new int[8] { 12, 33, 89, 21, 15, 29, 40, 52 };
     3        public int[] myResult;
     4         public MyBlogBase()
     5         {
     6             myPredicate = delegate(int curNum) 
     7             { if (curNum % 2 == 0) return true; 
     8               else return false; 
     9             };
    10         }  
    11         public void StartPredicate()
    12         {
    13             myResult = Array.FindAll(myNum, myPredicate);
    14         }

    上例中说明了Predicate的使用,FindAll方法中,参数2即是一个Predicate,在具体的执行中,每一个数组的元素都会执行指定的方法,如果满足要求返回true,并会被存放在结果集中,不符合的则被剔除,最终返回的集合,即是结果判断后想要的集合,此方法应用场景感觉像迭代中的yield。

  • 相关阅读:
    软件工程 speedsnail 第二次冲刺2
    软件工程 speedsnail 第二次冲刺1次
    软件工程 speedsnail 冲刺9
    软件工程 speedsnail 冲刺8
    软件工程 speedsnail 冲刺7
    软件工程 speedsnail 冲刺6
    软件工程 speedsnail 冲刺5
    软件工程 speedsnail 冲刺4
    软件工程 speedsnail 冲刺3
    软件工程 speedsnail 冲刺2
  • 原文地址:https://www.cnblogs.com/QQ931697811/p/4335476.html
Copyright © 2011-2022 走看看