闲着没事,写个委托、异步委托玩玩

在编程中,委托有利于解耦,同时也是异步编程的基础,但是由于书写的方式跟平常不太一样,所以委托就跟反射一样,比较难于接受。

委托是一种引用方法的类型。一旦为委托分配了方法,委托将与该方法具有完全相同的行为。委托方法的使用可以像其他任何方法一样,具有参数和返回值,委托是一种引用方法的类型。一旦为委托分配了方法,委托将与该方法具有完全相同的行为。委托方法的使用可以像其他任何方法一样,具有参数和返回值。

与委托的签名(由返回类型和参数组成)匹配的任何方法都可以分配给该委托。这样就可以通过编程方式来更改方法调用,还可以向现有类中插入新代码。只要知道委托的签名,便可以分配自己的委托方法。

将方法作为参数进行引用的能力使委托成为定义回调方法的理想选择。例如,可以向排序算法传递对比较两个对象的方法的引用。分离比较代码使得可以采用更通用的方式编写算法。

委托具有以下特点:

  • 委托类似于 C++ 函数指针,但它是类型安全的。

  • 委托允许将方法作为参数进行传递。

  • 委托可用于定义回调方法。

  • 委托可以链接在一起;例如,可以对一个事件调用多个方法。

  • 方法不需要与委托签名精确匹配。有关更多信息,请参见协变和逆变。

  • C# 2.0 版引入了匿名方法的概念,此类方法允许将代码块作为参数传递,以代替单独定义的方法。



以下,为委托与异步委托的实例代码:

None.gif using  System;
None.gif
using  System.Collections.Generic;
None.gif
using  System.Text;
None.gif
None.gif
namespace  TestWindowsApplication
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif    
public class Maths
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif        
public int add(int x, int y)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return x + y;
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
public int minus(int x, int y)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return x - y;
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

  1 None.gif using  System;
  2 None.gif using  System.Collections.Generic;
  3 None.gif using  System.ComponentModel;
  4 None.gif using  System.Data;
  5 None.gif using  System.Drawing;
  6 None.gif using  System.Text;
  7 None.gif using  System.Windows.Forms;
  8 None.gif
  9 None.gif namespace  TestWindowsApplication
 10 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 11InBlock.gif    public partial class Form1 : Form
 12ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 13InBlock.gif        //定义一个委托
 14InBlock.gif        public delegate int MyHandler(int x, int y);
 15InBlock.gif
 16InBlock.gif        public Form1()
 17ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 18InBlock.gif            InitializeComponent();
 19ExpandedSubBlockEnd.gif        }

 20InBlock.gif
 21InBlock.gif        private void Form1_Load(object sender, EventArgs e)
 22ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 23InBlock.gif
 24ExpandedSubBlockEnd.gif        }

 25InBlock.gif
 26InBlock.gif        private void button1_Click(object sender, EventArgs e)
 27ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 28InBlock.gif            int x = this.textBox1.Text == "" ? 0 : int.Parse(this.textBox1.Text);
 29InBlock.gif            int y = this.textBox2.Text == "" ? 0 : int.Parse(this.textBox2.Text);
 30InBlock.gif
 31InBlock.gif            Maths maths = new Maths();
 32InBlock.gif            //绑定到maths实例的add方法
 33InBlock.gif            MyHandler addhandler = new MyHandler(maths.add);
 34InBlock.gif            //调用
 35InBlock.gif            int addResult = addhandler(x, y);
 36InBlock.gif            MessageBox.Show(string.Format("{0} values: {1}", addhandler.Method.Name, addResult));
 37ExpandedSubBlockEnd.gif        }

 38InBlock.gif
 39InBlock.gif        private void button2_Click(object sender, EventArgs e)
 40ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 41InBlock.gif            int x = this.textBox1.Text == "" ? 0 : int.Parse(this.textBox1.Text);
 42InBlock.gif            int y = this.textBox2.Text == "" ? 0 : int.Parse(this.textBox2.Text);
 43InBlock.gif
 44InBlock.gif            StringBuilder sb = new StringBuilder();
 45InBlock.gif            Maths maths = new Maths();
 46InBlock.gif
 47InBlock.gif            MyHandler all = null;
 48InBlock.gif            //绑定到maths实例的add方法
 49InBlock.gif            MyHandler add = new MyHandler(maths.add);
 50InBlock.gif            //绑定到maths实例的minus方法
 51InBlock.gif            MyHandler minus = new MyHandler(maths.minus);
 52InBlock.gif
 53InBlock.gif            //链接
 54InBlock.gif            all += add;
 55InBlock.gif            all += minus;
 56InBlock.gif
 57InBlock.gif            //定义传入参数
 58ExpandedSubBlockStart.gifContractedSubBlock.gif            object[] param =dot.gif{ x, y };
 59InBlock.gif
 60InBlock.gif            //获取目标委托数组
 61InBlock.gif            Delegate[] delegates = all.GetInvocationList();
 62InBlock.gif            foreach (Delegate dg in delegates)
 63ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 64InBlock.gif                try
 65ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 66InBlock.gif                    //动态调用当前委托所表示的方法
 67InBlock.gif                    int addResult = (int)dg.DynamicInvoke(param);
 68InBlock.gif                    sb.AppendFormat("{0} values: {1}\n", dg.Method.Name, addResult);
 69ExpandedSubBlockEnd.gif                }

 70InBlock.gif                catch (Exception et)
 71ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 72InBlock.gif                    MessageBox.Show(et.Message);
 73ExpandedSubBlockEnd.gif                }

 74ExpandedSubBlockEnd.gif            }

 75InBlock.gif
 76InBlock.gif            MessageBox.Show(sb.ToString());
 77ExpandedSubBlockEnd.gif        }

 78InBlock.gif
 79InBlock.gif        private void button3_Click(object sender, EventArgs e)
 80ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 81InBlock.gif            int x = this.textBox1.Text == "" ? 0 : int.Parse(this.textBox1.Text);
 82InBlock.gif            int y = this.textBox2.Text == "" ? 0 : int.Parse(this.textBox2.Text);
 83InBlock.gif
 84InBlock.gif            Maths maths = new Maths();
 85InBlock.gif            //绑定到maths实例的add方法
 86InBlock.gif            MyHandler addhandler = new MyHandler(maths.add);
 87InBlock.gif
 88InBlock.gif            //异步调用开始
 89InBlock.gif            IAsyncResult ar = addhandler.BeginInvoke(x, y, nullnull);
 90InBlock.gif
 91InBlock.gif            //异步操作是否完成
 92InBlock.gif            while (!ar.IsCompleted)
 93ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 94InBlock.gif                //如果没完成,当前线程阻止时间为10毫秒
 95InBlock.gif                System.Threading.Thread.Sleep(10);
 96ExpandedSubBlockEnd.gif            }

 97InBlock.gif            //异步调用完成,返回结果
 98InBlock.gif            int addResult = addhandler.EndInvoke(ar);
 99InBlock.gif
100InBlock.gif            MessageBox.Show(string.Format("{0} values: {1}", addhandler.Method.Name, addResult));
101ExpandedSubBlockEnd.gif        }

102InBlock.gif
103ExpandedSubBlockEnd.gif    }

104ExpandedBlockEnd.gif}

转载于:https://www.cnblogs.com/dagecc/archive/2006/11/23/569320.html

猜你喜欢

转载自blog.csdn.net/weixin_33816300/article/details/93829577