3.0 面向对象 委托和事件 异常和错误
2013-06-27 20:54
309 查看
一、委托和事件
委托和事件这两个概念是完全配合的。委托仅仅是函数指针,那就是说,它能够引用函数,通过传递地址的机制完成。委托是一个类,当你对它实例化时,要提供一个引用函数,将其作为它构造函数的参数。事件则是委托的一种表现形式。委托的声明:[修饰符] delegate 返回类型 委托名(参数列表);
简单的委托
View Code
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Runtime.Remoting.Messaging; namespace ConsoleApp { public delegate int AddDelegate(int x, int y); class Program9 { static void Main(string[] args) { Console.WriteLine("--------客户端执行开始,即将调用异步"); Thread.CurrentThread.Name = "客户端线程Name"; Calculator cal = new Calculator(); AddDelegate del = new AddDelegate(cal.Add); string data = "客户端数据."; //异步完成后挂载的方法返回的数据 AsyncCallback callBack = new AsyncCallback(OnAddComplete); //异步完成后挂载方法 del.BeginInvoke(2, 5, callBack, data); // 异步调用方法 // 做某些其它的事情,模拟需要执行3秒钟 for (int i = 1; i <= 3; i++) { Thread.Sleep(TimeSpan.FromSeconds(i)); Console.WriteLine("{0}: 模拟执行其他事情 {1} 秒钟.", Thread.CurrentThread.Name, i); } Console.WriteLine("\n-------客户端执行完毕..."); Console.ReadKey(); } static void OnAddComplete(IAsyncResult asyncResult) { AsyncResult result = (AsyncResult)asyncResult; AddDelegate del = (AddDelegate)result.AsyncDelegate; string data = (string)asyncResult.AsyncState; int rtn = del.EndInvoke(asyncResult); Console.WriteLine("{0}: 异步返回值, {1}; Data: {2}\n", Thread.CurrentThread.Name, rtn, data); } } public class Calculator { public int Add(int x, int y) { if (Thread.CurrentThread.IsThreadPoolThread) { Thread.CurrentThread.Name = "异步线程Name"; } Console.WriteLine("--------异步开始!"); // 执行某些事情,模拟需要执行2秒钟 for (int i = 1; i <= 2; i++) { Thread.Sleep(TimeSpan.FromSeconds(i)); Console.WriteLine("{0}: 模拟执行事情 {1} 秒钟.", Thread.CurrentThread.Name, i); } Console.WriteLine("--------异步结束!"); return x + y; } } }
二、异常和错误 (try-catch-finally)
基类:System.Exception
try语句提供了一种机制来捕捉块执行过程中发生的异常。以下是它的三种可能的形式(s可多个catch):
●try-catch(s)
●try-finally
●try-catch(s)-finally
try{申请资源,如数据库连接,网络连接,打开文件等可能出现异常的代码}
catch(异常类型 e){处理异常一类型的异常}
finally{释放资源}
手动跑出异常:throw new System.Exception();
相关文章推荐
- PHP 的异常处理、错误的抛出及回调函数等面向对象的错误处理方法
- PyQt 如果异常未处理,抛入到事件循环,则无错误提示崩溃的解决方法
- 面向对象的委托和事件
- 面向对象——(10)委托与事件
- java种异常机制和事件委托机制
- 开发常见错误解决(5)WSE3.0未处理的SoapHeaderException,未处理的SoapHeader异常
- C#——面向对象——事件和委托——委托
- CITRIX 5.0,XML服务异常引出事件ID 31003和30016错误
- java种异常机制和事件委托机制
- PHP 的异常处理、错误的抛出及回调函数等面向对象的错误处理方法
- 开发常见错误解决(6)WSE3.0未处理的WebException,未处理的Web异常,基础连接以及关闭
- 面向对象——一起来复习委托与事件!
- 开发常见错误解决(6)WSE3.0未处理的WebException,未处理的Web异常,基础连接以及关闭
- PHP 的异常处理、错误的抛出及回调函数等面向对象的错误处理方法
- 开发常见错误解决(5)WSE3.0未处理的SoapHeaderException,未处理的SoapHeader异常
- 包文件错误导致resin出现out of memory异常
- 错误处理和异常处理,你用哪一个
- DNS 加载区域时的 9002错误解决方法(事件ID4521)
- 取消事件所有委托方法
- 初学事件委托