C#學習筆記:泛型委托Action 和Fun


(一)Action<T>和Fun<TResult>兩個委托的不同點:

Action<T>只能委托必須是無返回值的方法

Fun<TResult>只是委托必須有返回值的方法

(二)代碼演練

 

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


//方法一:顯式聲明了一個委托,並將對 實例方法的引用分配給其委托實例。
publicdelegatevoid ShowName();
publicdelegatevoid ShowNameWithParameter(string name);
publicdelegatevoid ShowAge(int age);
publicdelegatevoid ShowNameAndAge(string name, int age);
publicdelegateint ReturnName(string name);
namespace ActionDemo
{    
    publicclass Person
    {       
        privatestring instanceName;

        publicstring InstanceName
        {
            get { return instanceName; }
            set { instanceName = value; }
        }
        privateint instanceAge;

        publicint InstanceAge
        {
            get { return instanceAge; }
            set { instanceAge = value; }
        }
        public Person(string name,int age)
        {
            this.instanceName = name;
            this.instanceAge = age;
        }
        publicvoid DisplayName()
        {
            Console.WriteLine("Name:{0}",this.instanceName);
        }
        publicvoid DisplayName(string name)
        {
            Console.WriteLine("Name:{0}",name);
        }      
        publicvoid DisplayAge(int age)
        {
            Console.WriteLine("Age:{0}",age);
        }
        publicvoid DisplayNameAndAge(string name, int age)
        {
            Console.WriteLine(string.Format("Name:{0} And Age:{1} ",name,age));
        }
        publicint GetAgeByName(string name)
        {
            if(name==instanceName)
            {
                 return instanceAge;
            }
            else
            {
                return-1;
            }
           
        }
       
    }
    class Program
    {
        privatestaticvoid Print(string s)
        {
            Console.WriteLine(s);
        }
        
        
        staticvoid Main(string[] args)
        {
            #region Action<T>相關
            Person person =new Person("joetao",21);
            //非泛型委托
            //ShowName showName = new ShowName(name.DisplayName);
            //另一種寫法
            ShowName showName = person.DisplayName;
            showName();
            ShowNameWithParameter showNameWithParameter = person.DisplayName;
            showNameWithParameter(person.InstanceName);
            ShowAge showAge = person.DisplayAge;
            showAge(person.InstanceAge);
            ShowNameAndAge showNameAndAge = person.DisplayNameAndAge;
            showNameAndAge(person.InstanceName, person.InstanceAge);

            //泛型委托Action<T,...>這里指多個類型參數
            //Action<T,..>委托:只能委托無返回值(void)的方法。
            //(2)可以使用此委托以參數形式傳遞方法,而不用顯式聲明自定義的委托          
            Action actionShowName = person.DisplayName;
            actionShowName();
            Action<string> actionShowName1 = person.DisplayName;
            actionShowName1(person.InstanceName);
            Action<int> actionShowAge = person.DisplayAge;
            actionShowAge(person.InstanceAge);
            Action<string, int> actionShowNameAndAge = person.DisplayNameAndAge;
            actionShowNameAndAge(person.InstanceName, person.InstanceAge);

            //匿名泛型委托
            //(1)初步
            Action<string> actionPrintNameAtFirst;
            actionPrintNameAtFirst =delegate(string s) { Console.WriteLine("Name:{0}",s); };
            actionPrintNameAtFirst(person.InstanceName);
            //(2)簡化
            Action<string> actionprintName;
            actionprintName = s => Console.WriteLine("Name:{0}", s);
            actionprintName(person.InstanceName);

            //示例演示如何使用 Action<T> 委托來打印 List<T> 對象的內容
            //使用 Print 方法將列表的內容顯示到控制台上。 此外,C# 示例還演示如何使用匿名方法將內容顯示到控制台上
            //請注意該示例不顯式聲明 Action<T> 變量。 相反,它傳遞方法的引用,該方法采用單個參數而且不將值返回至 List<T>.ForEach 方法,其單個參數是一個 Action<T> 委托
            // 同樣,在 C# 示例 中,Action<T> 委托不被顯式地實例化,因為匿名方法的簽名匹配 List<T>.ForEach 方法所期望的 Action<T> 委托的簽名。
            List<String> names =new List<String>();
            names.Add("Bruce");
            names.Add("Alfred");
            names.Add("Tim");
            names.Add("Richard");          
            names.ForEach(Print);         
            names.ForEach(delegate(String name){Console.WriteLine(name);});

            #endregion

            #region Fun<TResultf>相關
            //泛型委托Func<T,...,TResult> 委托,這里可以有一個或多個或者沒有參數T,但必須有返回值並返回 TResult 參數所指定的類型的值
            //(1)必須有指定參數返回值。
            //(2)Lambda 表達式的基礎類型是泛型 Func 委托之一。 這樣能以參數形式傳遞 lambda 表達式,而不用顯式將其分配給委托。
            //(3)因為 System.Linq 命名空間中許多類型方法具有 Func<T, TResult> 參數,因此可以給這些方法傳遞 lambda 表達式,而不用顯式實例化 Func<T, TResult> 委托。

            //非泛型委托實現
            ReturnName returnName = person.GetAgeByName;
            Console.WriteLine("Age:{0}", returnName(person.InstanceName));

            //泛型委托實現
            Func<string, int> funReturnName = person.GetAgeByName;
            Console.WriteLine("Age:{0}",funReturnName(person.InstanceName));

            //泛型匿名委托實現
            //(1)初步
            Func<string, int> funReturnName1 =delegate(string s) {return person.GetAgeByName(s); };
            Console.WriteLine("Age:{0}", funReturnName1(person.InstanceName));
            //(2)優化
            Func<string, int> funReturnName2 = s => person.GetAgeByName(s);
            Console.WriteLine("Age:{0}", funReturnName2(person.InstanceName));

            //示例演示如何聲明和使用 Func<T, TResult> 委托
            //此示例聲明一個 Func<T, TResult> 變量,並為其分配了一個將字符串中的字符轉換為大寫的 lambda 表達式。
            //隨后將封裝此方法的委托傳遞給 Enumerable.Select 方法,以將字符串數組中的字符串更改為大寫。 
            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);

            #endregion
            Console.ReadKey();           
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;


//方法一:顯式聲明了一個委托,並將對 實例方法的引用分配給其委托實例。
publicdelegatevoid ShowName();
publicdelegatevoid ShowNameWithParameter(string name);
publicdelegatevoid ShowAge(int age);
publicdelegatevoid ShowNameAndAge(string name, int age);
publicdelegateint ReturnName(string name);
namespace ActionDemo
{    
    publicclass Person
    {       
        privatestring instanceName;

        publicstring InstanceName
        {
            get { return instanceName; }
            set { instanceName = value; }
        }
        privateint instanceAge;

        publicint InstanceAge
        {
            get { return instanceAge; }
            set { instanceAge = value; }
        }
        public Person(string name,int age)
        {
            this.instanceName = name;
            this.instanceAge = age;
        }
        publicvoid DisplayName()
        {
            Console.WriteLine("Name:{0}",this.instanceName);
        }
        publicvoid DisplayName(string name)
        {
            Console.WriteLine("Name:{0}",name);
        }      
        publicvoid DisplayAge(int age)
        {
            Console.WriteLine("Age:{0}",age);
        }
        publicvoid DisplayNameAndAge(string name, int age)
        {
            Console.WriteLine(string.Format("Name:{0} And Age:{1} ",name,age));
        }
        publicint GetAgeByName(string name)
        {
            if(name==instanceName)
            {
                 return instanceAge;
            }
            else
            {
                return-1;
            }
           
        }
       
    }
    class Program
    {
        privatestaticvoid Print(string s)
        {
            Console.WriteLine(s);
        }
        
        
        staticvoid Main(string[] args)
        {
            #region Action<T>相關
            Person person =new Person("joetao",21);
            //非泛型委托
            //ShowName showName = new ShowName(name.DisplayName);
            //另一種寫法
            ShowName showName = person.DisplayName;
            showName();
            ShowNameWithParameter showNameWithParameter = person.DisplayName;
            showNameWithParameter(person.InstanceName);
            ShowAge showAge = person.DisplayAge;
            showAge(person.InstanceAge);
            ShowNameAndAge showNameAndAge = person.DisplayNameAndAge;
            showNameAndAge(person.InstanceName, person.InstanceAge);

            //泛型委托Action<T,...>這里指多個類型參數
            //Action<T,..>委托:只能委托無返回值(void)的方法。
            //(2)可以使用此委托以參數形式傳遞方法,而不用顯式聲明自定義的委托          
            Action actionShowName = person.DisplayName;
            actionShowName();
            Action<string> actionShowName1 = person.DisplayName;
            actionShowName1(person.InstanceName);
            Action<int> actionShowAge = person.DisplayAge;
            actionShowAge(person.InstanceAge);
            Action<string, int> actionShowNameAndAge = person.DisplayNameAndAge;
            actionShowNameAndAge(person.InstanceName, person.InstanceAge);

            //匿名泛型委托
            //(1)初步
            Action<string> actionPrintNameAtFirst;
            actionPrintNameAtFirst =delegate(string s) { Console.WriteLine("Name:{0}",s); };
            actionPrintNameAtFirst(person.InstanceName);
            //(2)簡化
            Action<string> actionprintName;
            actionprintName = s => Console.WriteLine("Name:{0}", s);
            actionprintName(person.InstanceName);

            //示例演示如何使用 Action<T> 委托來打印 List<T> 對象的內容
            //使用 Print 方法將列表的內容顯示到控制台上。 此外,C# 示例還演示如何使用匿名方法將內容顯示到控制台上
            //請注意該示例不顯式聲明 Action<T> 變量。 相反,它傳遞方法的引用,該方法采用單個參數而且不將值返回至 List<T>.ForEach 方法,其單個參數是一個 Action<T> 委托
            // 同樣,在 C# 示例 中,Action<T> 委托不被顯式地實例化,因為匿名方法的簽名匹配 List<T>.ForEach 方法所期望的 Action<T> 委托的簽名。
            List<String> names =new List<String>();
            names.Add("Bruce");
            names.Add("Alfred");
            names.Add("Tim");
            names.Add("Richard");          
            names.ForEach(Print);         
            names.ForEach(delegate(String name){Console.WriteLine(name);});

            #endregion

            #region Fun<TResultf>相關
            //泛型委托Func<T,...,TResult> 委托,這里可以有一個或多個或者沒有參數T,但必須有返回值並返回 TResult 參數所指定的類型的值
            //(1)必須有指定參數返回值。
            //(2)Lambda 表達式的基礎類型是泛型 Func 委托之一。 這樣能以參數形式傳遞 lambda 表達式,而不用顯式將其分配給委托。
            //(3)因為 System.Linq 命名空間中許多類型方法具有 Func<T, TResult> 參數,因此可以給這些方法傳遞 lambda 表達式,而不用顯式實例化 Func<T, TResult> 委托。

            //非泛型委托實現
            ReturnName returnName = person.GetAgeByName;
            Console.WriteLine("Age:{0}", returnName(person.InstanceName));

            //泛型委托實現
            Func<string, int> funReturnName = person.GetAgeByName;
            Console.WriteLine("Age:{0}",funReturnName(person.InstanceName));

            //泛型匿名委托實現
            //(1)初步
            Func<string, int> funReturnName1 =delegate(string s) {return person.GetAgeByName(s); };
            Console.WriteLine("Age:{0}", funReturnName1(person.InstanceName));
            //(2)優化
            Func<string, int> funReturnName2 = s => person.GetAgeByName(s);
            Console.WriteLine("Age:{0}", funReturnName2(person.InstanceName));

            //示例演示如何聲明和使用 Func<T, TResult> 委托
            //此示例聲明一個 Func<T, TResult> 變量,並為其分配了一個將字符串中的字符轉換為大寫的 lambda 表達式。
            //隨后將封裝此方法的委托傳遞給 Enumerable.Select 方法,以將字符串數組中的字符串更改為大寫。 
            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);

            #endregion
            Console.ReadKey();           
        }
    }
}

 


免責聲明!

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



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