.net中的委託方法

來源:互聯網
上載者:User

標籤:io   os   使用   ar   for   sp   art   cti   on   

Func 接受輸入參數(可多個殘數),並且返回指定的輸出TResult

Action接受參數(只有一個),返回void

Predicate 有一個輸入參數,如果輸入參數符合指定的條件,返回true,否則fasle.

具體代碼實現如下:


一,public delegate TResult Func<in T, out TResult>( T arg )
封裝一個具有一個參數並返回 TResult 參數指定的類型值的方法。
實現一,顯式聲明自訂委託實現字元轉換
using System;
delegate string ConvertMethod(string inString);  
public class DelegateExample
{
   public static void Main()
   {
      // 轉成大寫
      ConvertMethod convertMeth = UppercaseString;
      string name = "Dakota";
      // Use delegate instance to call UppercaseString method
      Console.WriteLine(convertMeth(name));
   }
 
   private static string UppercaseString(string inputString)
   {
      return inputString.ToUpper();
   }
}

使用匿名方法:
 using System;
public class DelegateExample
{
   public static void Main()
   {
      // 轉成大寫
      Func<string,string> convertMeth = delegate(string inputstr)
      {
           return inputstr.ToUpper();
      }
      string name = "Dakota";
      Console.WriteLine(convertMeth(name));
   }
 
}

使用lambda運算式
 using System;
public class lambdaExample
{
   public static void Main()
   {
      // 轉成大寫
      Func<string,string> convert = inputstr=>inputstr.ToUpper();

      string name = "Dakota";
      Console.WriteLine(convert(name));
   }
 
}

樣本again
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
 
static class Func
{
   static void Main(string[] args)
   {
      Func<string, string> selector = str => str.ToUpper();
 
      // 建立一個字串數組
      string[] words = { "orange", "apple", "Article", "elephant" };
      IEnumerable<String> aWords = words.Select(selector);
 
      //輸出
      foreach (String word in aWords)
         Console.WriteLine(word);
   }
}       

二,public delegate void Action<in T>( T obj )
該方法只有一個參數並且不傳回值,
T為此委託封裝的方法的參數類型。此型別參數是逆變。
using System;
using System.Windows.Forms;
public class TestAnonMethod
{
   public static void Main()
   {
      Action<string> messageTarget;  
 
      if (Environment.GetCommandLineArgs().Length > 1)
         messageTarget = delegate(string s) { MessageBox.Show(s); };
      else
         messageTarget = delegate(string s) { Console.WriteLine(s); };
 
    //lambda運算式
      if (Environment.GetCommandLineArgs().Length > 1)
         messageTarget = s => MessageBox.Show(s);  
      else
         messageTarget = s => Console.WriteLine(s);

      messageTarget("Hello, World!");
   }
 
}

//列印list<string>
using System;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        List<String> names = new List<String>();
        names.Add("Bruce");
        names.Add("Alfred");
        names.Add("Tim");
        names.Add("Richard");
 
        // 使用print答應list的值
        names.ForEach(Print);
 
        // 同上,使用匿名方法
        names.ForEach(delegate(String name)
        {
            Console.WriteLine(name);
        });

        //同上, lambda運算式
      names.ForEach(name=>console.WriteLine(name));
    }
 
    private static void Print(string s)
    {
        Console.WriteLine(s);
    }
}


Predicate 聲明:public delegate bool Predicate<in T>(T obj)
表示定義一組條件並確定指定對象是否符合這些條件的方法。
public class HockeyTeam
    {
        private string _name;
        private int _founded;
        public HockeyTeam(string name, int year)
        {
            _name = name;
            _founded = year;
        }
        public string Name
        {
            get { return _name; }
        }
        public int Founded
        {
            get { return _founded; }
        }
    }

    public class Example
    {
        
        public static void Main()
        {            
        List<HockeyTeam> teams = new List<HockeyTeam>{
                                         new HockeyTeam("Detroit Red Wings", 1926),
                                         new HockeyTeam("Chicago Blackhawks", 1926),
                                         new HockeyTeam("San Jose Sharks", 1991),
                                         new HockeyTeam("Montreal Canadiens", 1909),
                                         new HockeyTeam("St. Louis Blues", 1967) };            
            //1 >>1,2,3三種方式都可實現,選擇其中一種就行。
            Random rnd = new Random();
            int[] years = { 1920, 1930, 1980, 2000 };
            int foundedBeforeYear = years[rnd.Next(0, years.Length)];
            Console.WriteLine("Teams founded before {0}:", foundedBeforeYear);
            foreach (var team in teams.FindAll(x => x.Founded <= foundedBeforeYear))
                Console.WriteLine("{0}: {1}", team.Name, team.Founded);
            //2 //如果找到與指定謂詞定義的條件匹配的第一個元素Array.Find(HockeyTeam,Predicate<HockeyTema>)
            Predicate<HockeyTeam> find = FindTeam;
            HockeyTeam ht = Array.Find(teams.ToArray(), find);
            Console.WriteLine("{0}: {1}", ht.Name, ht.Founded);

            //3

     //Random rnd = new Random();
            //int[] years = { 1920, 1930, 1980, 2000 };
            //int foundedBeforeYear = years[rnd.Next(0, years.Length)];
            //HockeyTeam ht4 = teams.Find(t => t.Founded < foundedBeforeYear);
            //Console.WriteLine("{0}: {1}", ht4.Name, ht4.Founded);
        }

        private static bool FindTeam(HockeyTeam ht)
        {
            Random rnd = new Random();
            int[] years = { 1920, 1930, 1980, 2000 };
            int foundedBeforeYear = years[rnd.Next(0, years.Length)];
            return ht.Founded <= foundedBeforeYear;
        }

    }

.net中的委託方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.