.Net 委托 delegate 學習

来源:https://www.cnblogs.com/Rookieflying/archive/2019/02/15/10386198.html
-Advertisement-
Play Games

一、什麼是委托: 委托是定址方法的.NET版本,使用委托可以將方法作為參數進行傳遞。委托是一種特殊類型的對象,其特殊之處在於委托中包含的只是一個活多個方法的地址,而不是數據。 二、使用委托: 關鍵字:delegate 1.聲明: public delegate void DoNothing();// ...


一、什麼是委托: 委托是定址方法的.NET版本,使用委托可以將方法作為參數進行傳遞。委托是一種特殊類型的對象,其特殊之處在於委托中包含的只是一個活多個方法的地址,而不是數據。   二、使用委托: 關鍵字:delegate 1.聲明:       public delegate void DoNothing();//定義一個無返回值,無參數的委托      public delegate int GetNum(int i); //定義有一個返回值int ,參數int 的委托 2.創建方法: public static void DoSome()//無參無返回值的方法
{
Console.WriteLine("DoSome");
} public static int TotalNum(int num)//有一個返回值int ,參數int 的方法
{
return num * num;
}   3.註冊委托: DoNothing doNothing = new DoNothing(DoSome); //或者直接寫出DoNothing doNothing = DoSome;   GetNum getNum = AddNum;//註冊委托   4.執行委托 doNothing.Invoke();//執行委托  也可以直接 doNothing(); Console.WriteLine(getNum.Invoke(10));//執行委托並且列印   三、委托的意義 傳遞方法;把方法包裹起來, 傳遞邏輯。非同步多線程執行   四、.net framework3.5之後,系統定義好了2個委托,開發儘量使用框架自帶委托,儘量使用Action和Func Action 無返回值委托,Func 有返回值委托   Action要使用參數,就寫Action<int,string,double> 最多可以到16個   Func要使用參數,就寫成Func<int,string,double> 最多可以到17個, 最後一個為返回值,現在這個返回的就是double類型   Action act = DoSome;//Action 無返回值委托 act.Invoke();    Func<int,int> func = new Func<int,int>(TotalNum)  ; func(10);     五、多播委托 Action doSome = new Action(DoSome);
doSome += new Action(DoSome);
doSome += DoSome;   doSome();//按順序執行,最後結果是執行3次DoSome方法   doSome -= DoSome;//減少一次DoSome執行   doSome();//按順序執行,最後結果是執行2次DoSome方法   多播委托,按順序執行,多播委托,用Action, Func帶返回值的只執行完後,只得到最後一個結果,所以沒有意義。   委托使用案例:一個學生類,一個學生管理靜態類,可以通過委托,實現學生集合的篩選
 public class Student
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int ClassId { get; set; }

        public int Age { get; set; }
    }

    public static  class StudentManager
    {
        public static List<Student> students = new List<Student>()
        {
            new Student(){ Id=1,Name="張三",ClassId=1001,Age=15 },
            new Student(){ Id=2,Name="李四",ClassId=1001,Age=15 },
            new Student(){ Id=3,Name="王五",ClassId=1001,Age=15 },
            new Student(){ Id=4,Name="趙六",ClassId=1001,Age=15 },
            new Student(){ Id=5,Name="楊冪",ClassId=1001,Age=14 },
            new Student(){ Id=6,Name="範冰冰",ClassId=101,Age=14 },
            new Student(){ Id=7,Name="張學友",ClassId=1021,Age=14},
            new Student(){ Id=8,Name="張三1",ClassId=1021,Age=16 },
            new Student(){ Id=9,Name="張三2",ClassId=1001,Age=17 },
            new Student(){ Id=10,Name="張三3",ClassId=1001,Age=15 },
            new Student(){ Id=11,Name="張三4",ClassId=1001,Age=19 },
            new Student(){ Id=12,Name="張三5",ClassId=1001,Age=25 },
            new Student(){ Id=13,Name="張三6",ClassId=1003,Age=25 },
            new Student(){ Id=14,Name="張三7",ClassId=1003,Age=25 },
            new Student(){ Id=15,Name="張三8",ClassId=1003,Age=25 },
            new Student(){ Id=16,Name="張三9",ClassId=1003,Age=25 },
            new Student(){ Id=17,Name="張三0",ClassId=1003,Age=25 },
            new Student(){ Id=18,Name="張三11",ClassId=1003,Age=15 },
            new Student(){ Id=19,Name="張三a",ClassId=1011,Age=15 },
            new Student(){ Id=20,Name="張三b",ClassId=1011,Age=15 },
            new Student(){ Id=21,Name="張三c",ClassId=1011,Age=15 },
            new Student(){ Id=22,Name="張三d",ClassId=1011,Age=15 },
            new Student(){ Id=23,Name="張三e",ClassId=1011,Age=15 },
            new Student(){ Id=24,Name="張三f",ClassId=1011,Age=15 },
            new Student(){ Id=25,Name="張三g",ClassId=3001,Age=15 },
            new Student(){ Id=26,Name="張三h",ClassId=3001,Age=13 },
            new Student(){ Id=27,Name="張三i",ClassId=3001,Age=13 },
            new Student(){ Id=28,Name="張三j",ClassId=3001,Age=13 },
            new Student(){ Id=29,Name="張三k",ClassId=3001,Age=13 },
        };

        public static List<Student> FindStudents(Func<Student,bool> func)
        {
            List<Student> stus = new List<Student>();

            foreach (var item in students)
            {
                if (func(item))
                {
                    stus.Add(item);
                }
            }
            return stus;
        }
        

        /// <summary>
        /// 查找ClassId為3001的學生
        /// </summary>
        /// <param name="student">學生</param>
        /// <returns>是否為3001班級的學生</returns>
        public static bool GetClassId(Student student)
        {
            if (student.ClassId==3001)
            {
                return true;
            }

            return false;
            
        }
        /// <summary>
        /// 年齡大於20的學生
        /// </summary>
        /// <param name="student"></param>
        /// <returns></returns>
        public static bool GetBigAge(Student student)
        {
            if (student.Age>20)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 年齡大於15 並且ClassId為1021
        /// </summary>
        /// <param name="student"></param>
        /// <returns></returns>
        public static bool GetStuByClassIdAndAge(Student student)
        {
            if (student.Age > 15 && student.ClassId==1021)
            {
                return true;
            }
            return false;
        }

    }

下麵這個是在Main方法中執行查詢學生

//List<Student> stus = StudentManager.students;

            //Console.WriteLine("姓名---年齡---班級--編號");
            //foreach (var item in stus)
            //{
            //    Console.WriteLine(item.Name+"---"+item.Age+"---"+item.ClassId+"---"+item.Id);
            //}

            List<Student> stus1=  StudentManager.FindStudents(StudentManager.GetStuByClassIdAndAge);
           
            Console.WriteLine("姓名---年齡---班級--編號");
            foreach (var item in stus1)
            {
                Console.WriteLine(item.Name + "---" + item.Age + "---" + item.ClassId + "---" + item.Id);
            }

 



您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 輸入:只能輸入A-Z(不區分大小寫),0-9和下劃線; 第一行輸入應輸入字元串,第二行輸入實際輸入字元串。 輸出:按大寫輸出缺少的字元,每個字元輸出一次。 註意: 1、由於不區分大小寫,則需要將小寫字母識別為大寫字母; 2、保證每個字元只出現一次。 思路: 1、將所有的字母都轉化為大寫字母; 2、挨 ...
  • 前言 前段時間,博客和論壇都放到的阿裡雲新購的三年 T5 實例伺服器上,等都轉移過去才發現,所謂的 T5 實例只能滿足10% 的 CPU 峰值。期間經歷了各種卡頓、死機,最終又把博客單獨遷移了回來。靜態文件走 CDN,文章都 Redis,以為萬事大吉了就。 群壓 然並卵,有一天,群里有網友說要壓測我 ...
  • 啟動了兩個goroutine,並完成一些工作。在各自迴圈的每次迭代之後,在goroutine 會使用LoadInt64 來檢查shutdown 變數的值。這個函數會安全地返回shutdown 變數的一個副本。如果這個副本的值為1,goroutine 就會跳出迴圈並終止。 ...
  • 父進程退出時,子進程會如何?如何確保父進程退出時,子進程也退出? ...
  • 一、閉包 1.舉例 註意:inner()是局部變數,在全局範圍不可調用(即不能直接調用inner()函數),但是在法二中,在執行完 f = outer() 之後,outer()函數就已經結束,執行f()的時候卻可以調用inner()函數,並輸出x的值,這是因為outer()里 return 的 in ...
  • 原因:python是64位的python,而windll.LoadLibrary只能由32位的python使用 參考: 64位Python調用32位DLL方法(一) 解決方法:使用32位的python(切記版本不要太新,本人一開始使用最新的32位python3.7.2再次報錯,換成python3.6 ...
  • 1.atomic包里的幾個函數以及sync包里的mutex類型,提供瞭解決方案2.原子函數能夠以很底層的加鎖機制來同步訪問整型變數和指針3.atomic.AddInt64(&counter, 1)的原理是強制同一時刻只能有一個goroutine運行並完成這個加法操作 ...
  • 迭代器的執行流程,以及說明可迭代對象不一定是迭代器,但迭代器一定是可迭代對象 實例1 實例1的優化 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...