C#中的Action和Func和Predicate


一、【action<>】指定那些只有輸入參數,沒有返回值的委托

用了Action之后呢:

就是相當於省去了定義委托的步驟了。

演示代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EventDemo
{
    class Program
    {
        public delegate void myDelegate(string str);  
        public static void HellowChinese(string strChinese)  
        {  
            Console.WriteLine("Good morning," + strChinese);  
            Console.ReadLine();  
        }  

        static void Main(string[] args)
        {
            //Delegate的代碼
            myDelegate d = new myDelegate(HellowChinese);
            d("Mr wang");

            //用了Action之后呢
            Action<string> action = HellowChinese;
            action("Spring.");

            Console.ReadLine();
        }
    }
}
View Code

 

二、func<> 這個和上面的那個是一樣的,區別是這個有返回值!

語法:

Func<參數,返回值>變量名=函數名 

Lambda表達式的調用方式
語法:(顯示類型的參數列表)=>{語句}
eg:
Func<int,int,string>func=(x,y)=>(x*y).Tostring();
Console.WriteLine(fun(5,20));
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace EventDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //類似委托功能
            Func<string, int> test = TsetMothod;
            Console.WriteLine(test("123"));
            Func<string, int> test1 = TsetMothod;


            //只需要調用這個類就可以減少重復的代碼
            CallMethod<string>(test1, "123");
            //或者采用這種
            CallMethod<string>(new Func<string, int>(TsetMothod), "123");
            CallMethod(new Func<string, int>(TsetMothod), "123");

            Func<int, double, decimal, string> testFun = TestFun;
            double b = 2.3;
            decimal c = 666.7m;
            string strtestFun = testFun(1, b, c);
            Console.WriteLine("Func<int, double, decimal, string> testFun={0}", strtestFun);

            Console.ReadKey();
        }

        public static string TestFun(int a, double b, decimal c)
        {
            return "TestFun";
        }

        public static int TsetMothod(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return 1;
            }
            return 0;
        }

        public static void CallMethod<T>(Func<T, int> func, T item)
        {
            try
            {
                int i = func(item);
                Console.WriteLine(i);
            }
            catch (Exception e)
            {

            }
            finally
            {

            }
        }
    }
}
View Code
Predicate 泛型委托
  表示定義一組條件並確定指定對象是否符合這些條件的方法。此委托由 Array 和 List 類的幾種方法使用,用於在集合中搜索元素。
 
public delegate bool Predicate<T>(T obj);
類型參數介紹:
   T: 要比較的對象的類型。
   obj: 要按照由此委托表示的方法中定義的條件進行比較的對象。
   返回值:如果 obj 符合由此委托表示的方法中定義的條件,則為 true;否則為 false。
看下面代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EventDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string>() { "Mike", "Rose", "Steve" };
            var mike = list.Find(new Predicate<string>(HaveLengthFive));
            Console.WriteLine(mike);
            Console.ReadLine();
        }
        static bool HaveLengthFive(string value)
        {
            return value.Length == 5;
        }
    }
}
View Code

延伸:
  除了上面提到的外,你完全可以使用Predicate 定義新的方法,來加強自己代碼。

public class GenericDelegateDemo
{
    List<String> listString = new List<String>()
    {
        "One","Two","Three","Four","Fice","Six","Seven","Eight","Nine","Ten"
    };

    public String GetStringList(Predicate<String> p)
    {
        foreach(string item in listString)
        {
            if (p(item))
                return item;
        }
        return null;
    }

    public bool ExistString()
    {
        string str = GetStringList((c) => { return c.Length <= 3 && c.Contains('S'); });
        if (str == null)
            return false;
        else
            return true;
    }
}
View Code

 

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM