C#中的Action和Func和Predicate

其實他們都是委託【代理】的簡寫形式。

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

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();
        }
    }
}

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

語法:
Func<參數,返回值>變量名=函數名 
Lambda表達式的調用方式
語法:(顯示類型的參數列表)=>{語句}
eg:
Func<int,int,string>func=(x,y)=>(x*y).Tostring();
Console.WriteLine(fun(5,20));
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
            {
            }
        }
    }
}

Predicate 泛型委託
  表示定義一組條件並確定指定對象是否符合這些條件的方法。此委託由 Array 和 List 類的幾種方法使用,用於在集合中搜索元素。

public delegate bool Predicate<T>(T obj);
類型參數介紹:
   T: 要比較的對象的類型。
   obj: 要按照由此委託表示的方法中定義的條件進行比較的對象。
   返回值:如果 obj 符合由此委託表示的方法中定義的條件,則爲 true;否則爲 false。
看下面代碼:
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;
        }
    }
}
延伸:
  除了上面提到的外,你完全可以使用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;
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章