.NET (五)委託第五講:內置委託Predicate

    // 摘要: 
    //     表示定義一組條件並肯定指定對象是否符合這些條件的方法。
    //
    // 參數: 
    //   obj:
    //     要按照由此委託表示的方法中定義的條件進行比較的對象。
    //
    // 類型參數: 
    //   T:
    //     要比較的對象的類型。
    //
    // 返回結果: 
    //     若是 obj 符合由此委託表示的方法中定義的條件,則爲 true;不然爲 false。
    public delegate bool Predicate<in T>(T obj);

Predicate委託根據條件進行篩選,返回 是 或 否。spa

下面篩選客戶名稱,查詢出以字母z開頭的客戶:code

   class Class5
    {
        static void Main(String[] args)
        {
            Customer c1 = new Customer() { Name = "zhangsan", Age = 18 };
            Customer c2 = new Customer() { Name = "lisi", Age = 17 };
            Customer c3 = new Customer() { Name = "wangwu", Age = 20 };
            Customer c4 = new Customer() { Name = "xiaoming", Age = 10 };
            Customer c5 = new Customer() { Name = "zhangchao", Age = 25 };
            List<Customer> list = new List<Customer>();
            list.Add(c1);
            list.Add(c2);
            list.Add(c3);
            list.Add(c4);
            list.Add(c5);


            Predicate<Customer> predicate = new Predicate<Customer>(Choose);
            List<Customer> query = list.FindAll(predicate);


            ObjectDumper.Write(query);

        }


        public static  bool Choose(Customer c)
        {
            if (c.Name.StartsWith("z"))
            {
                return true;
            }
            return false;

        }
    }

List集合中的findAll方法接受一個Predicate委託類型。對象

匿名委託:blog

            //代碼演進
            List<Customer> query = list.FindAll(delegate(Customer c)
            {
                if (c.Name.StartsWith("z"))
                {
                    return true;
                }
                return false;
            });

Lamada:it

            List<Customer> query = list.FindAll((Customer c)=>
            {
                if (c.Name.StartsWith("z"))
                {
                    return true;
                }
                return false;
            });

 

 

總結:委託定義的是方法的類型。返回值和參數必須與方法相同。io

.NET 爲咱們定義了4大內置委託,他們是:class

Action:無返回值List

Func: 有返回值gc

Comparison:返回整數,比較兩個對象程序

Predicate:返回bool ,根據條件篩選

委託能夠將方法做爲參數傳遞,靈活使用委託可讓咱們的程序更加簡潔,結構清晰。

相關文章
相關標籤/搜索