随笔2010.01.25
用例契约
用例:使用事件委托 |
概要: .NET事件委托的编码过程 |
基本事件流: 定义一个事件参数类,继承System.EventArgs; 声明一个委托A,假设为public delegate A(EventArgs e,int code); 声明一个事件委托public event A CustomHanddler(它看作是一个特殊的委托); 定义一个事件处理方法(回调函数),它和委托A有相同的参数列表; 为事件附加事件处理方法,事件注册、订阅; 事件监听:设置触发事件的条件; |
其他事件流: |
异常事件流: |
|
前置条件: 了解事件委托机制; |
后置条件: 完成能通过Debug的事件委托程序,运行成功; |
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
///示例代码
public delegate void DealCustomExption(object sender, CustomEventArgs e);//声明委托
public event DealCustomExption DealCustomExceptionEvent;//声明事件
public Form1()
{
InitializeComponent();
this.DealCustomExceptionEvent += new DealCustomExption(ProcessStepOne);//订阅事件
this.DealCustomExceptionEvent += new DealCustomExption(ProcessStepTwo);
}
public void ProcessStepOne(object sender, CustomEventArgs e)
{
textBox1.BackColor = System.Drawing.Color.Pink;
textBox1.Text = e.CustomEventDescription+":"+"自定义异常抛出_事件处理1";
}
public void ProcessStepTwo(object sender, CustomEventArgs e)
{
textBox2.BackColor = System.Drawing.Color.Pink;
this.BackColor = System.Drawing.Color.AliceBlue;
textBox2.Text += e.CustomEventDescription+":"+"自定义异常抛出_事件处理2";
}
private void button1_Click(object sender, EventArgs e)
{
try
{
textBox1.Text = GetStringByDllMethod();
textBox2.Text = GetStringBySomeInterfaceMethod();
}
catch (CustomException ce)
{ //事件监听程序,当发生异常时候出发事件
DealCustomExceptionEvent(this,new CustomEventArgs());
label1.Text = ce.CustomDescription;
}
catch (System.Exception ex)
{
textBox1.Text = ex.ToString();
textBox2.Text = ex.Message.ToString();
}
}
public event DealCustomExption DealCustomExceptionEvent;//声明事件
public Form1()
{
InitializeComponent();
this.DealCustomExceptionEvent += new DealCustomExption(ProcessStepOne);//订阅事件
this.DealCustomExceptionEvent += new DealCustomExption(ProcessStepTwo);
}
public void ProcessStepOne(object sender, CustomEventArgs e)
{
textBox1.BackColor = System.Drawing.Color.Pink;
textBox1.Text = e.CustomEventDescription+":"+"自定义异常抛出_事件处理1";
}
public void ProcessStepTwo(object sender, CustomEventArgs e)
{
textBox2.BackColor = System.Drawing.Color.Pink;
this.BackColor = System.Drawing.Color.AliceBlue;
textBox2.Text += e.CustomEventDescription+":"+"自定义异常抛出_事件处理2";
}
private void button1_Click(object sender, EventArgs e)
{
try
{
textBox1.Text = GetStringByDllMethod();
textBox2.Text = GetStringBySomeInterfaceMethod();
}
catch (CustomException ce)
{ //事件监听程序,当发生异常时候出发事件
DealCustomExceptionEvent(this,new CustomEventArgs());
label1.Text = ce.CustomDescription;
}
catch (System.Exception ex)
{
textBox1.Text = ex.ToString();
textBox2.Text = ex.Message.ToString();
}
}