您的位置:首页 > 其它

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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: