C#中匿名方法與委托的關系介紹
當對2個數實現加減乘除,其中的一個解決方案是通過委托來實現。如下:
class Program { private delegate int CaculateDel(int num1, int num2); static void Main(string[] args) { CaculateDel caculateDel = Add; Console.WriteLine(caculateDel.Invoke(1,2).ToString()); Console.ReadKey(); } static int Add(int num1, int num2) { return num1 + num2; } }
以上,把Add方法賦值給了CaculateDel類型的委托變量。
如果用匿名方法來實現,就是:
class Program { private delegate int CaculateDel(int num1, int num2); static void Main(string[] args) { CaculateDel caculateDel = delegate(int num1, int num2) { return num1 + num2; }; Console.WriteLine(caculateDel.Invoke(1,2).ToString()); Console.ReadKey(); } }
可見,匿名方法就是委托,使用匿名方法有了更好的靈活性,不需要事先把方法寫"死"。
如果我們使用System.Diagnostics的Stopwatch的實例方法Reset、Start、Stop等來重置、開始、結束Stopwatch,用Stopwatch的ElapsedTickes屬性來顯示時間,我們可以發(fā)現匿名方法的效率比較高。
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析
這篇文章主要介紹了C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析,以實例形式較為詳細的講述了.NET Framework里面提供的三種Timer具體用法,需要的朋友可以參考下2014-10-10使用快捷鍵在Unity中快速鎖定和解鎖Inspector右上角的鎖功能
這篇文章主要為大家介紹了使用快捷鍵在Unity中快速鎖定和解鎖Inspector右上角的鎖功能詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08