• C#委托基础


     
     
    C#委托基础1——委托基础
     

    委托和其委托的方法必须具有相同的签名。签名相同:1.参数类型相同 2.参数数量相同 3.返回值一致

    例一

    1. class Program  
    2. {  
    3.         public delegate int MathMethod(int x, int y);  
    4.          
    5.         public int Add(int a, int b)  
    6.         {  
    7.             return a + b;  
    8.         }  
    9.  
    10.         static void Main(string[] args)  
    11.         {  
    12.             MathMethod mm;  
    13.             Program p = new Program();  
    14.             mm = p.Add;// 相当于一个方法的容器  
    15.             Console.WriteLine("计算结果为{0}",mm(7,6));  
    16.             Console.ReadLine();  
    17.         }  

    例二

    1. class Program  
    2. {  
    3.          
    4.         public delegate double MathMethod(double x, double y);  
    5.  
    6.         double Add(double a, double b)  
    7.         {  
    8.             return a + b;  
    9.         }  
    10.  
    11.         double Subtract(double a, double b)  
    12.         {  
    13.             return a + b;  
    14.         }  
    15.  
    16.         double Multiply(double a, double b)  
    17.         {  
    18.             return a * b;  
    19.         }  
    20.  
    21.         double Divide(double a, double b)  
    22.         {  
    23.             return a / b;  
    24.         }  
    25.  
    26.         void DoCalculate(MathMethod mm)  
    27.         {  
    28.             Console.WriteLine("请输入第一个数");  
    29.             double x = Convert.ToDouble(Console.ReadLine());  
    30.  
    31.             Console.WriteLine("请输入第二个数");  
    32.             double y = Convert.ToDouble(Console.ReadLine());  
    33.  
    34.             Console.WriteLine("结果{0}",mm(x, y));  
    35.             Console.ReadLine();  
    36.              
    37.         }  
    38.  
    39.         static void Main(string[] args)  
    40.         {  
    41.             MathMethod mm;  
    42.             Program p = new Program();  
    43.             mm = p.Divide;  
    44.             p.DoCalculate(mm);  
    45.         }  

     -----------------------------------------------------------

    C#委托基础2——多路委托

    多路委托

    1. class Program  
    2.     {  
    3.         public delegate void SayThingToS(string s);  
    4.  
    5.         void SayHello(string s)  
    6.         {  
    7.             Console.WriteLine("你好{0}", s);  
    8.         }  
    9.  
    10.         void SayGoodBye(string s)  
    11.         {  
    12.             Console.WriteLine("再见{0}", s);  
    13.         }  
    14.  
    15.         static void Main(string[] args)  
    16.         {  
    17.             // 方式一  
    18.             SayThingToS say1, say2, say3, say4;  
    19.             Program p = new Program();  
    20.             say1 = p.SayHello;  
    21.             say1("xy"); // 你好xy  
    22.  
    23.             say2 = p.SayGoodBye;  
    24.             say2("xy"); // 再见xy  
    25.  
    26.             say3 = say1 + say2;  
    27.             say3("xy"); // 你好xy,再见xy  
    28.  
    29.             say4 = say3 - say1;  
    30.             say4("xy"); // 再见xy  
    31.  
    32.  
    33.             // 方式二  
    34.             SayThingToS s1 = new SayThingToS(p.SayHello);  
    35.             s1 += new SayThingToS(p.SayGoodBye);  
    36.             s1("xy"); // 你好xy,再见xy  
    37.  
    38.             SayThingToS s2 = new SayThingToS(p.SayHello);  
    39.             s2 += new SayThingToS(p.SayGoodBye);             
    40.             s2 -= new SayThingToS(p.SayHello);  
    41.             s2("xy"); // 再见xy  
    42.         }  
    43.     } 

     -----------------------------------------------------------

    C#委托基础3——泛型委托

    泛型委托

    1. class Program  
    2. {  
    3.         // 泛型委托,与普通委托类似,不同之处只在于使用泛型委托要指定泛型参数          
    4.         public delegate T MyGenericDelegate<T>(T obj1,T obj2);  
    5.  
    6.         int AddInt(int x, int y)  
    7.         {  
    8.             return x + y;  
    9.         }  
    10.  
    11.         string AddString(string s1, string s2)  
    12.         {  
    13.             return s1 + s2;  
    14.         }  
    15.          
    16.         static void Main(string[] args)  
    17.         {  
    18.             Program p = new Program();  
    19.              
    20.             MyGenericDelegate<int> intDel;  
    21.             intDel = p.AddInt;  
    22.             Console.WriteLine("int代理的值是{0}", intDel(100, 200));  
    23.  
    24.             MyGenericDelegate<string> stringDel;  
    25.             stringDel = p.AddString;  
    26.             Console.WriteLine("string代理的值是{0}", stringDel("aaa""bbb"));  
    27.         }  

    为了方便开发,.NET基类库针对在实际开发中最常用的情形提供了几个预定义好的委托,这些预定义委托用得很广,比如在编写lambda表达式和开发并行计算程序时经常要用到他们。就是下面我的几篇博客需要介绍的内容。

     -----------------------------------------------------------

    C#委托基础4——泛型委托Func

    为了方便开发,.NET基类库针对在实际开发中最常用的情形提供了几个预定义好的委托,这些预定义委托用得很广,比如在编写lambda表达式和开发并行计算程序时经常要用到他们。

    预定义泛型委托Func

    1. class Program  
    2. {  
    3.         double AddInt(int x, int y)  
    4.         {  
    5.             return x + y;  
    6.         }  
    7.  
    8.         string AddString(string s1, string s2)  
    9.         {  
    10.             return s1 + s2;  
    11.         }  
    12.  
    13.         static void Main(string[] args)  
    14.         {  
    15.             Program p = new Program();  
    16.  
    17.             // 以为前两个参数为int,他们运行的结果为double,最后一个参数与AddInt返回值一致  
    18.             Func<intintdouble> funcInt = p.AddInt;  
    19.             Console.WriteLine("funcInt的值为{0}", funcInt(100300));  
    20.  
    21.             Func<string, string, string> funcString = p.AddString;  
    22.             Console.WriteLine("funcString的值为{0}", funcString("aaa""bbb"));  
    23.         }  

     -----------------------------------------------------------

    C#委托基础5——泛型委托Action

    为了方便开发,.NET基类库针对在实际开发中最常用的情形提供了几个预定义好的委托,这些预定义委托用得很广,比如在编写lambda表达式和开发并行计算程序时经常要用到他们


    对于函数返回值为空的情形,可以使用Action泛型委托

    1. class Program  
    2. {  
    3.         // 对于函数返回值为空的情形,可以使用Action泛型委托  
    4.         void Showstring(string s)  
    5.         {  
    6.             Console.WriteLine("显示的string值为{0}",s);  
    7.         }  
    8.  
    9.         static void Main(string[] args)  
    10.         {  
    11.             Program p = new Program();  
    12.  
    13.             Action<string> showstring = p.Showstring;  
    14.             showstring("xy");  
    15.         }  

     -----------------------------------------------------------

    C#委托基础6——泛型委托Predicate
     

    此委托返回一个bool值,该委托通常引用一个"判断条件函数"。

    需要指出的是,判断条件一般为“外部的硬性条件”,比如“大于50”,而不是由数据自身指定,不如“查找数组中最大的元素就不适合”。

    例一

    1. class Program  
    2. {  
    3.         bool IsGreaterThan50(int i)  
    4.         {  
    5.             if (i > 50)   
    6.                 return true;  
    7.             else 
    8.                 return false;  
    9.         }  
    10.  
    11.         static void Main(string[] args)  
    12.         {  
    13.             Program p=new Program();  
    14.  
    15.             List<int> lstInt = new List<int>();  
    16.             lstInt.Add(50);  
    17.             lstInt.Add(80);  
    18.             lstInt.Add(90);  
    19.  
    20.             Predicate<int> pred = p.IsGreaterThan50;  
    21.             int i = lstInt.Find(pred);                         // 找到匹配的第一个元素,此处为80  
    22.             Console.WriteLine("大于50的第一个元素为{0}",i);  
    23.  
    24.             List<int> all = lstInt.FindAll(pred);  
    25.             for (int j = 0; j < all.Count(); j++)  
    26.             {  
    27.                 Console.WriteLine("大于50的数组中元素为{0}", all[j]);  // 找出所有匹配条件的  
    28.             }  
    29.             Console.ReadLine();  
    30.         }  
    31. }  
    32.  

    例二

    1. class Staff  
    2. {  
    3.         private double salary;  
    4.  
    5.         public double Salary  
    6.         {  
    7.             get { return salary; }  
    8.             set { salary = value; }  
    9.         }  
    10.  
    11.         private string num;  
    12.  
    13.         public string Num  
    14.         {  
    15.             get { return num; }  
    16.             set { num = value; }  
    17.         }  
    18.  
    19.         public override string ToString()  
    20.         {  
    21.             return "Num......" + num + "......" + "......" + "Salary......" + salary;  
    22.         }  
    23. }  
    24.  
    25.  
    26. class Program  
    27. {  
    28.         bool IsSalaryGreaterThan5000(Staff s)  
    29.         {  
    30.             if (s.Salary > 5000)  
    31.                 return true;  
    32.             else 
    33.                 return false;  
    34.         }  
    35.  
    36.         static void Main(string[] args)  
    37.         {  
    38.             Program p = new Program();  
    39.  
    40.             List<Staff> allStaff = new List<Staff>  
    41.             {  
    42.                 new Staff{Num="001",Salary=9999.9},  
    43.                 new Staff{Num="002",Salary=8991},  
    44.                 new Staff{Num="003",Salary=10000.8},  
    45.                 new Staff{Num="004",Salary=4999.99}  
    46.             };  
    47.  
    48.             Predicate<Staff> s = p.IsSalaryGreaterThan5000;  
    49.             Staff theFirstOne = allStaff.Find(s);  
    50.             Console.WriteLine(theFirstOne);              // 找出第一个  
    51.              
    52.             List<Staff> all = allStaff.FindAll(s);  
    53.             for (int i = 0; i < all.Count(); i++)  
    54.             {  
    55.                 Console.WriteLine(all[i]);               // 找出所有满足条件的  
    56.             }  
    57.             Console.ReadLine();  
    58.         }  
    59. }  
    60.  

     -----------------------------------------------------------

    C#委托基础7——匿名方法
     
     
    1. class Program  
    2. {  
    3.         double AddInt(int x, int y)  
    4.         {  
    5.             return x + y;  
    6.         }  
    7.  
    8.         string AddString(string s1, string s2)  
    9.         {  
    10.             return s1 + s2;  
    11.         }  
    12.  
    13.         static void Main(string[] args)  
    14.         {  
    15.             Program p = new Program();、  
    16.  
    17.             // 以为前两个参数为int,他们运行的结果为double,最后一个参数与AddInt返回值一致  
    18.             Func<intintdouble> funcInt = p.AddInt;  
    19.             Console.WriteLine("funcInt的值为{0}", funcInt(100, 300));  
    20.  
    21.             Func<stringstringstring> funcString = p.AddString;  
    22.             Console.WriteLine("funcString的值为{0}", funcString("aaa""bbb"));  
    23.  
    24.             // 匿名方法  
    25.             Func<floatfloatfloat> fucFloat = delegate(float x, float y)  
    26.             {  
    27.                 return x + y;  
    28.             };  
    29.             Console.WriteLine("funcFloat的值为{0}", fucFloat(190.7F, 99999.9F));  
    30.             Console.ReadLine();  
    31.         }  
    32. }  

     -----------------------------------------------------------

    C#委托基础8——lambda表达式

    1. class Program  
    2. {  
    3.         double AddInt(int x, int y)  
    4.         {  
    5.             return x + y;  
    6.         }  
    7.  
    8.         string AddString(string s1, string s2)  
    9.         {  
    10.             return s1 + s2;  
    11.         }  
    12.  
    13.         static void Main(string[] args)  
    14.         {  
    15.             Program p = new Program();             
    16.  
    17.             // 以为前两个参数为int,他们运行的结果为double,最后一个参数与AddInt返回值一致  
    18.             Func<intintdouble> funcInt = p.AddInt;  
    19.             Console.WriteLine("funcInt的值为{0}", funcInt(100, 300));  
    20.  
    21.             Func<stringstringstring> funcString = p.AddString;  
    22.             Console.WriteLine("funcString的值为{0}", funcString("xy""xy"));  
    23.  
    24.  
    25.             // 匿名方法  
    26.             Func<floatfloatfloat> fucFloat = delegate(float x, float y)  
    27.             {  
    28.                 return x + y;  
    29.             };  
    30.             Console.WriteLine("funcFloat的值为{0}", fucFloat(190.7F, 99999.9F));  
    31.  
    32.             // Lambda表达式  
    33.             Func<stringstringstring> funString2 = (x, y) => (x + y);  
    34.             Console.WriteLine("funString2的值为{0}", funString2("xy""xy"));  
    35.             Console.ReadLine();  
    36.         }  

     -----------------------------------------------------------

    C#委托基础9——Invoke与委托

    例一

    1. delegate void AppendStringCallback(string text);  
    2.  
    3. private void AppendString(string txt)  
    4. {  
    5.      this.listView1.Items.Add(txt);  
    6. }  
    7.  
    8.  
    9. private void ReceiveDate()  
    10. {  
    11.      AppendStringCallback appendStringCallback = new AppendStringCallback(AppendString);  
    12.      this.Invoke(appendStringCallback, new object[]   
    13.                    { string.Format("{0},{1},{2}", str1, str2 + "号", iepAddress.ToString()) });  
    14. }  
    15.  

    例二

    1. namespace ThreadPoolDemo    
    2. {    
    3.     public partial class ThreadForm : Form    
    4.     {    
    5.         // 定义delegate以便Invoke时使用    
    6.         private delegate void SetProgressBarValue(int value);     
    7.          
    8.  
    9.         // 跟SetProgressBarValue委托相匹配的方法    
    10.         private void SetProgressValue(int value)    
    11.         {    
    12.            progressBar.Value = value;    
    13.         }    
    14.  
    15.         // 使用Invoke方法来设置进度条    
    16.         private void RunWithInvoke()    
    17.         {    
    18.             int value = progressBar.Value;    
    19.             while (value< progressBar.Maximum)    
    20.             {    
    21.                 // 如果是跨线程调用    
    22.                 if (InvokeRequired)    
    23.                 {    
    24.                     this.Invoke(new SetProgressBarValue(SetProgressValue), value++);    
    25.                 }    
    26.                 else   
    27.                 {    
    28.                     progressBar.Value = ++value;    
    29.                 }    
    30.             }    
    31.         }     
    32.  
    33.         public ThreadForm()    
    34.         {    
    35.             InitializeComponent();    
    36.         }     
    37.       
    38.         private void btnInvoke_Click(object sender, EventArgs e)    
    39.         {    
    40.             progressBar.Value = 0;    
    41.             Thread thread = new Thread(new ThreadStart(RunWithInvoke));    
    42.             thread.Start();    
    43.         }     
    44.  
    45.      }    
    46. }   

     -----------------------------------------------------------

    C#委托基础系列原于2011年2月份发表在我的新浪博客中,现在将其般至本博客。

    本文出自 “IT徐胖子的专栏” 博客,请务必保留此出处http://woshixy.blog.51cto.com/5637578/1070976

  • 相关阅读:
    js实现好看的图案 加勒比海盗(php拍黄片)
    网站优化的几点 下
    php算法 快速排序 选择算法 冒泡算法
    javascript中null和undefined的区别
    tp3 上传图片出现上传根目录不存在!请尝试手动创建:./Public/Uploads/ 错误解决思路
    网站优化的几点 上
    tp5框架 报错非法请求:admin/index/index
    通过response向服务器用Io流写入图片
    解决客户端向服务器写中文时乱码问题
    setInterval()设置页面5,4,3,2,1秒后跳转
  • 原文地址:https://www.cnblogs.com/hrx521/p/3354930.html
Copyright © 2020-2023  润新知