我爱学习第一天(委托)
生活随笔
收集整理的這篇文章主要介紹了
我爱学习第一天(委托)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
---恢復內容開始---
1.delegate
一般用法
delegate void WriteValue(string vale);//申明一個委托,參數是string類型,無返回值static void Main(string[] args){WriteValue write = new WriteValue(WriteLine);//實例化委托write("喝水");//調用 Console.ReadKey();}public static void WriteLine(string value) {for (int i = 0; i < 5; i++){Console.WriteLine("第{0}次{1}", i, value);}} View Code?
匿名委托
delegate void WriteValue(string vale);static void Main(string[] args){WriteValue write = delegate (string value) { Console.Write(value); };write("喝水");Console.ReadKey();} View Code?
使用lambda表達式
如需要傳入多個參數,需要用"()"將參數包括起來,用","隔開.
delegate void WriteValue(string vale,string value1);static void Main(string[] args){WriteValue write = (value,value1) => { Console.Write(value);Console.Write(value1); };write("喝水","吃飯");Console.ReadKey();} View Code?
多播委托
delegate void WriteValue(string value);static void Main(string[] args){WriteValue value1 = new WriteValue(Write);value1 += new WriteValue(WriteLine);value1("s");Console.ReadKey();}public static void WriteLine(string value) {Console.WriteLine("幫我倒杯卡布奇洛,謝謝");}public static void Write(object value) {Console.WriteLine("多加點糖,謝謝");} View Code?
2.Func<T,E>
T表示參數類型,E表示返回值類型. Func<T1,T2,T3,E>表示有三個參數,類型分別為T1,T2,T3,返回值為E,以此類推.Func<E>表示沒有參數,返回值類型為E.
delegate void WriteValue(string value);static void Main(string[] args){Func<string, int> func = Length;Console.WriteLine(func("哈哈哈"));Console.ReadKey();}public static int Length(string value) {return value.Length;} View Code?
3.Action<T>
Action<T1,T2,T3>表示有三個參數,無返回值,以此類推.
static void Main(string[] args){Action<string, string> action = Length;action("吃飯飯", "喝水水");Console.ReadKey();}public static void Length(string value,string value1) {Console.WriteLine(value);Console.WriteLine(value1);} View Code?
4.Predicate<T>:表示定義一組條件并確定指定對象是否符合這些條件的方法。該委托返回的是一個bool類型的值,如果比較滿足條件 .只能有一個參數.
static void Main(string[] args){Predicate<int> predicate = Max;Console.WriteLine(predicate(12).ToString());Console.ReadKey();}public static bool Max(int value) {return value > 0;} View Code?
?
?
---恢復內容結束---
轉載于:https://www.cnblogs.com/lzyqq/p/11309461.html
總結
以上是生活随笔為你收集整理的我爱学习第一天(委托)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ELK 构建 MySQL 慢日志收集平台
- 下一篇: 流程流转相关业务与流转的分离