注:一下是个人在练习C#时所使用的例子,有一部分是自己写的,一部分来自于《C# 高级编程》,特此声明。如需引用,请标明作者
1: try_catch_fianlly语法
using System;
namespace Wrox.ProCSharp.AdvancedCSharp
{
public class MainEntryPoint
{
public static void Main()
{
string userInput;
while (true)
{
try
{
Console.Write("Input a number between 0 and 5 " + "(or just hit return to exit)> ");
userInput = Console.ReadLine();
if (userInput == "")
break;
int index = Convert.ToInt32(userInput);
if (index < 0 || index > 5)
throw new IndexOutOfRangeException("You typed in " + userInput);
Console.WriteLine("Your number was " + index);
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("Exception: " +"Number should be between 0 and 5. " + e.Message);
}
catch (Exception e)
{
Console.WriteLine("An exception was thrown. Message was: " + e.Message);
}
catch
{
Console.WriteLine("Some other exception has occurred");
}
finally
{
Console.WriteLine("Thank you");
}
}
}
}
}
2:代表(delegate)
注意,这两种的输出结果是不同的,大家可以直接去运行一下,看看:
(1)形式1
using System;
namespace Wrox.ProCSharp.AdvancedCSharp
{
delegate double DoubleOp(double x);
class MainEntryPoint
{
static void Main()
{
/******************************************************************************
* *
* 代表数组,注意和“+”的形式区别
* Console.WriteLine("Using operations[{0}]:", i);
ProcessAndDisplayNumber(operations[i], 2.0);
ProcessAndDisplayNumber(operations[i], 7.94);
ProcessAndDisplayNumber(operations[i], 1.414);
*
* *****************************************************************************/
DoubleOp [] operations =
{
new DoubleOp(MathsOperations.MultiplyByTwo),
new DoubleOp(MathsOperations.Square)
};
for (int i=0 ; i<operations.Length ; i++)
{
Console.WriteLine("Using operations[{0}]:", i);
ProcessAndDisplayNumber(operations[i], 2.0);
ProcessAndDisplayNumber(operations[i], 7.94);
ProcessAndDisplayNumber(operations[i], 1.414);
Console.WriteLine();
Console.ReadLine();
}
}
static void ProcessAndDisplayNumber(DoubleOp action, double value)
{
double result = action(value);
Console.WriteLine("Value is {0}, result of operation is {1}", value, result);
}
}
class MathsOperations
{
public static double MultiplyByTwo(double value)
{
return value*2;
}
public static double Square(double value)
{
return value*value;
}
}
}
(2)形式2
using System;
namespace Wrox.ProCSharp.AdvancedCSharp
{
delegate void DoubleOp(double value);
class MainEntryPoint
{
static void Main()
{
/*****************************************************************************
*
*
* DoubleOp operations = new DoubleOp(MathsOperations.MultiplyByTwo);
operations += new DoubleOp(MathsOperations.Square);
operations+=new DoubleOp(MathsOperations.www);
* 注意代表“+”的作用
*
*
*
* ****************************************************************************/
DoubleOp operations = new DoubleOp(MathsOperations.MultiplyByTwo);
operations += new DoubleOp(MathsOperations.Square);
operations+=new DoubleOp(MathsOperations.www);
ProcessAndDisplayNumber(operations, 2.0);
ProcessAndDisplayNumber(operations, 7.94);
ProcessAndDisplayNumber(operations, 1.414);
Console.WriteLine();
Console.ReadLine();
}
static void ProcessAndDisplayNumber(DoubleOp action, double value)
{
Console.WriteLine("/nProcessAndDisplayNumber called with value = " + value);
action(value);
}
}
class MathsOperations
{
public static void MultiplyByTwo(double value)
{
double result = value*2;
Console.WriteLine("Multiplying by 2: {0} gives {1}", value, result);
}
public static void Square(double value)
{
double result = value*value;
Console.WriteLine("Squaring: {0} gives {1}", value, result);
}
public static void www(double value)
{
Console.WriteLine("ddddddddddddd");
}
}
}
3:String与StringBuilder对比
注:其命名空间为System.Text
using System;
using System.Text;
namespace Wrox.ProCSharp.StringEncoder
{
class MainEntryPoint
{
static void Main(string[] args)
{
string greetingText = "Hello from all the guys at Wrox Press. ";
greetingText += "We do hope you enjoy this book as much as we enjoyed writing it.";
for(int i = (int)'z'; i>=(int)'a' ; i--)
{
char Old = (char)i;
char New = (char)(i+1);
greetingText = greetingText.Replace(Old, New);
}
for(int i = (int)'Z'; i>=(int)'A' ; i--)
{
char Old = (char)i;
char New = (char)(i+1);
greetingText = greetingText.Replace(Old, New);
}
Console.WriteLine("Encoded:/n" + greetingText);
/*******************************************************************************
*
*
* StringBuilder 属于System.Text的命名空间
*
*
* *******************************************************************************/
StringBuilder greetingBuilder =new StringBuilder("Hello from all the guys at Wrox Press. ", 150);
greetingBuilder.Append("We do hope you enjoy this book as much as we enjoyed writing it");
for(int i = (int)'z'; i>=(int)'a' ; i--)
{
char Old = (char)i;
char New = (char)(i+1);
greetingBuilder = greetingBuilder.Replace(Old, New);
}
for(int i = (int)'Z'; i>=(int)'A' ; i--)
{
char Old = (char)i;
char New = (char)(i+1);
greetingBuilder = greetingBuilder.Replace(Old, New);
}
Console.WriteLine("Encoded:/n" + greetingBuilder.ToString());
/*****************************************************************
*
*时间的利用DateTime.Now.Second
*
* **************************************************************/
StringBuilder sb=new StringBuilder();
sb.Append("UTC");
sb.Append(DateTime.Now.Hour);
sb.Append(DateTime.Now.Second);
Console.WriteLine(sb);
Console.ReadLine();
}
}
}
4:关键字ref
using System;
namespace Wrox.ProCSharp.Basics
{
class ParameterTest
{
/* ************************************************
*
* 关键字ref,表示引用!
*
* ************************************************/
static void SomeFunction(int[] ints, ref int i)
{
ints[0] = 100;
i = 100;
}
public static int Main()
{
int i = 0;
int[] ints = { 0, 1, 2, 4, 8 };
// Display the original values
Console.WriteLine("i = " + i);
Console.WriteLine("ints[0] = " + ints[0]);
Console.WriteLine("Calling SomeFunction...");
// After this method returns, ints will be changed,
// but i will not
SomeFunction(ints, ref i);
Console.WriteLine("i = " + i);
Console.WriteLine("ints[0] = " + ints[0]);
Console.ReadLine();
return 0;
}
}
}
5:命名空间
using System;
namespace Wrox.ProCSharp.Basics
{
class Client
{
public static void Main()
{
MathLib mathObj = new MathLib();
Console.WriteLine(mathObj.Add(7,8));
Console.ReadLine();
}
}
}
/****************************************************************
*
* 定义相同的命名空间
*
* ****************************************************************/
namespace Wrox.ProCSharp.Basics
{
public class MathLib
{
public int Add(int x, int y)
{
return x + y;
}
}
}
6:不规则数组的声明和使用
using System;
namespace Wrox.ProCSharp.Basics
{
class MainEntryPoint
{
static void Main()
{
// Declare a two-dimension jagged array of authors' names
/************************************************************************
*
*
* 非规则数组的声明和定义
* string[][] novelists = new string[3][];
novelists[0] = new string[] {"Fyodor", "Mikhailovich", "Dostoyevsky"};
novelists[1] = new string[] {"James", "Augustine", "Aloysius", "Joyce"};
novelists[2] = new string[] {"Miguel", "de Cervantes", "Saavedra"};
* **********************************************************************
*
*
*
* C# Copy Codepublic int GetLength ( int dimension)
C++ Copy Codepublic:int GetLength ( int dimension)
*
* 得到第一维的长度
*
*
* **********************************************************************/
string[][] novelists = new string[3][];
novelists[0] = new string[] { "Fyodor", "Mikhailovich", "Dostoyevsky" };
novelists[1] = new string[] { "James", "Augustine", "Aloysius", "Joyce" };
novelists[2] = new string[] { "Miguel", "de Cervantes", "Saavedra" };
// Loop through each novelist in the array
int i;
for (i = 0; i < novelists.GetLength(0); i++)
{
// Loop through each name for the novelist
int j;
for (j = 0; j < novelists[i].GetLength(0); j++)
{
// Display current part of name
Console.Write(novelists[i][j] + " ");
}
// Start a new line for the next novelist
Console.Write("/n");
}
Console.ReadLine();
}
}
}
7:格式输出
/* * *****************************************************************
*
*
* 字符 说明 示例 输出
C 或c
货币
Console.Write("{0:C}", 2.5);
Console.Write("{0:C}", -2.5);
$2.50
($2.50)
D 或d
十进制数
Console.Write("{0:D5}", 25);
00025
E 或e
科学型
Console.Write("{0:E}", 250000);
2.500000E+005
F 或f
固定点
Console.Write("{0:F2}", 25);
Console.Write("{0:F0}", 25);
25.00
25
G 或g
常规
Console.Write("{0:G}", 2.5);
2.5
N 或n
数字
Console.Write("{0:N}", 2500000);
2,500,000.00
X 或x
十六进制
Console.Write("{0:X}", 250);
Console.Write("{0:X}", 0xffff);
FA
FFFF
*
* *****************************************************************/
using System;
namespace Wrox.ProCSharp.Basics
{
class MyFirstCSharpClass
{
static void Main()
{
Console.WriteLine("This isn't at all like Java!");
double d = 0.234;
int i=666;
Console.WriteLine("{0:C}", d);
Console.WriteLine("{0:E}", d);
Console.WriteLine("{0:X}", i);
Console.ReadLine();
}
}
}
9: 镶套结构体的定义
using System;
namespace ConsoleApplication1
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//结构体也可以直接定义
student stu;
stu._age=22;
stu._name="mqt";
//小数默认是double 类型,要使用float 类型,必须在后面加f,另外一种是decimal 类型,必须加M
stu._weight=130.4f;
stu._address._city="shanghai";
stu._address._room="414";
Console.WriteLine(stu._address._city);
//结构体new 出来
student stu1=new student();
stu1._address._city="shandongwucheng";
Console.WriteLine(stu1._address._city);
Console.ReadLine();
}
}
//结构体的定义
public struct student
{
public string _name;
public int _age;
public float _weight;
//镶套结构体
public struct address
{
public string _room;
public string _city;
}
//镶套结构体的定义
public address _address;
}
}
10 关键字typeof ,as ,is 的应用,并且验证多态性
using System;
namespace typeof_is_as
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//类型版别typeof();
int i;
Console.WriteLine(typeof(int));
Console.WriteLine(typeof(man));
//对镶套类的类型判断应该这样student_man.people
Console.WriteLine(typeof(student_man.people));
//is操作符号,返回false or true
student_man st_man=new student_man();
Console.WriteLine("student_man is a man?::{0}",st_man is man);
Console.WriteLine("student_man is a man?::{0}",st_man is student_man);
Console.WriteLine("student_man is a man?::{0}",st_man is man);
//as操作符号,返回类型
man man1=st_man as man;
man1.output();
man1.output1();
Console.ReadLine();
}
}
class man
{
private string high;
virtual public void output()
{
high = "你好,这里是华东师范大学计算机系,欢迎访问我的Blog";
Console.WriteLine(high);
}
public void output1()
{
high = "呵呵,我是在基类中:因为基类中是非虚拟函数,所以这里不是多态";
Console.WriteLine(high);
}
}
class student_man:man
{
private int age;
private string major;
public class people
{
private string name;
}
override public void output()
{
Console.WriteLine("呵呵,我是在派生类中的:这是由于多态的作用,动态邦定了");
}
public void output1()
{
Console.WriteLine("验证多态性,看是不是应用了大态");
}
}
}
11:装箱与拆箱
using System;
//********************************************************
/*装箱过程其过程相当于有一个中间类Int_Box
* class Int_Box
* {
* public int value;
* public Int_Box(int t)
* {
* value=t;
* }
* public override string ToString()
* {
* return value.ToString();
* }
* }
* Int_Box temp=new Int_Box(10);
* Object obj=temp;
* *******************************************************/
namespace Box_UnBox
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//装箱过程
int i=10;
object obj=i;
i=20;
Console.WriteLine("int:i={0}",i);
Console.WriteLine("object:obj={0}",obj.ToString());
//拆箱过程
int j=(int)obj;
Console.WriteLine("int : j={0}",j);
Console.WriteLine("object:obj={0}" ,obj.ToString());
j=20;
Console.WriteLine("int : j={0}",j);
Console.WriteLine("object:obj={0}",obj.ToString() );
Console.ReadLine();
//
// TODO: 在此处添加代码以启动应用程序
//
}
}
}
12:操作的重载
using System;
namespace overwrite_operator
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
Complex com=new Complex(10,10);
com.Output();
com++;
com.Output();
Complex com2=new Complex(20,20);
Complex com3=new Complex(0,0);
com3=com2+com;
com3.Output();
Console.ReadLine();
//
// TODO: 在此处添加代码以启动应用程序
//
}
}
class Complex
{
//字段
private float _real;
private float _img;
//构造函数
public Complex(float real,float img)
{
_real=real;
_img=img;
}
//属性
public float real_value
{
get
{
return _real;
}
set
{
_real=value;
}
}
//属性
public float img_value
{
get
{
return _img;
}
{
_img=value;
set
}
}
//一元操作符的重载
public static Complex operator +(Complex com1,Complex com2)
{
Complex com=new Complex(0,0);
com.img_value=com1.img_value+com2.real_value;
com.real_value=com1.real_value+com2.real_value;
return com;
}
//二元操作符的重载
public static Complex operator++(Complex com1)
{
Complex com=new Complex(0,0);
com.real_value=com1.real_value+1;
com.img_value=com1.img_value+1;
return com;
}
public void Output()
{
Console.WriteLine(real_value.ToString()+"+"+img_value.ToString()+"i");
}
}
}
13:索引函数(this[])和属性函数( set/get)
using System;
namespace index
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
person per1=new person("mqt2003");
per1["phone_number"]="13482451786";
per1["fax_number"]="6212632";
per1.Output();
Console.ReadLine();
}
}
//一string 为索引的类
public class person
{
private string phone_number;
private string fax_number;
private string name;
public person()
{
}
public person(string name1)
{
this.name=name1;
}
public string person_name
{
get
{
return name;
}
set
{
name=value;
}
}
//索引函数,以this 为关键字,其中使用get /和set关键字,相当于属性的扩充
public string this[string type]
{
set
{
string up=type.ToLower();
switch(up)
{
case "phone_number":
phone_number=value;
break;
case "fax_number":
fax_number=value;
break;
default:
break;
}
}
get
{
string up=type.ToLower();
switch(up)
{
case "phone_number":
return phone_number;
case "fax_number":
return fax_number;
default:
return null;
}
}
}
public void Output()
{
Console.WriteLine("the person's name is {0}",name);
Console.WriteLine("his phone number is {0}",phone_number);
Console.WriteLine("his fax_number is {0}", fax_number);
}
}
}
14:事件(Event)
此事件符合.NET的C#事件格式
using System;
namespace Events
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
long speed;
speed=long.Parse(Console.ReadLine());
CheckSpeed check=new CheckSpeed();
DoSomething something=new DoSomething();
//将响应事件函数和激发事件函数绑定,只要一激发事件,就通过代表调用响应事件函数
check.myEvent+=new self_delegate(something.SlowDown);
check.CheckLimit(speed);
Console.ReadLine();
}
}
//自己定义的,派生自EventArgs
public class self_event:EventArgs
{
//类的字段
private long speed;
public self_event(long speed)
{
this.speed=speed;
}
//类的属性
public long get_speed
{
get
{
return speed ;
}
}
public string WarningMessage
{
get
{
return("Warning");
}
}
}
public class CheckSpeed
{
//通过关键字event,声明一个myEvent,并且将其和自定义代表绑定
public event self_delegate myEvent;
//定义激发事件函数,并且符合.NET标准,即参数为(object, eventArgs)
public void CheckLimit(long speed)
{
if(speed>60)
{
self_event speed_self_event=new self_event(speed);
myEvent(this,speed_self_event);//激发事件
}
else
{
Console.WriteLine("OK");
}
}
}
//定义一个代表
public delegate void self_delegate(object sender,self_event e);
//响应事件函数,通过代表对激发的事件做出响应
public class DoSomething
{
public void SlowDown(object sender,self_event e)
{
Console.WriteLine(" wrong,warning!!!!");
}
}
}
15:文件读取和写入
using System;
using System.IO;
//文件的输入输出的class 分别定义与StreamReader和StreamWriter
namespace stream_read_write
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
//@符号为“逐字字符串”
string file_name=@"C:/Documents and Settings/Administrator/Desktop/input.txt";
StreamReader freader=File.OpenText(file_name);
StreamWriter fwriter=File.CreateText(@"C:/Documents and Settings/Administrator/Desktop/outfile.txt");
string buffer;
while((buffer=freader.ReadLine())!=null)
{
fwriter.WriteLine(buffer);
}
//注意关闭文件
freader.Close();
fwriter.Close();
//
// TODO: 在此处添加代码以启动应用程序
//
}
}
}
16:规则和不规则数组的定义和使用
using System;
namespace mqt
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class Class1
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
//规则的二维数组
string [,] str=new string[3,4];
for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
str[i,j]="aaaa"+i.ToString()+j.ToString();
}
for(int i=0;i<3;i++)
{
for(int j=0;j<4;j++)
Console.WriteLine(str[i,j]);
}
//不规则的二维数组
string [][] str2=new string[3][];
for(int i=0;i<3;i++)
{
str2[i]=new string [i+3];
}
for(int i=0;i<3;i++)
for(int j=0;j<str2[i].Length;j++)
str2[i][j]="ddddddddddd"+i.ToString()+j.ToString();
for(int i=0;i<3;i++)
for(int j=0;j<str2[i].Length;j++)
Console.WriteLine(str2[i][j]);
Console.ReadLine();
}
}
}
17:哈希表的使用
using System;
using System.Text;
/*********************************************
* 集和命名空间
********************************************/
using System.Collections;
namespace Wrox.ProCSharp.SocialSecurityNumbers
{
class MainEntryPoint
{
static void Main()
{
TestHarness harness = new TestHarness();
harness.Run();
}
}
class TestHarness
{
/***************************************************************
*
* 哈希表
*
* *************************************************************/
Hashtable employees = new Hashtable(31);
public void Run()
{
EmployeeID idMortimer = new EmployeeID("B001");
EmployeeData mortimer = new EmployeeData(idMortimer, "Mortimer", 100000.00M);
EmployeeID idArabel = new EmployeeID("W234");
EmployeeData arabel= new EmployeeData(idArabel, "Arabel Jones", 10000.00M);
employees.Add(idMortimer, mortimer);
employees.Add(idArabel, arabel);
while (true)
{
try
{
Console.Write("Enter employee ID (format:A999, X to exit)> ");
string userInput = Console.ReadLine();
userInput = userInput.ToUpper();
if (userInput == "X")
return;
EmployeeID id = new EmployeeID(userInput);
DisplayData(id);
}
catch (Exception e)
{
Console.WriteLine("Exception occurred. Did you use the correct format for the employee ID?");
Console.WriteLine(e.Message);
Console.WriteLine();
}
Console.WriteLine();
}
}
private void DisplayData(EmployeeID id)
{
object empobj = employees[id];
if (empobj != null)
{
EmployeeData employee = (EmployeeData)empobj;
Console.WriteLine("Employee: " + employee.ToString());
}
else
Console.WriteLine("Employee not found: ID = " + id);
}
}
class EmployeeData
{
private string name;
private decimal salary;
private EmployeeID id;
public EmployeeData(EmployeeID id, string name, decimal salary)
{
this.id = id;
this.name = name;
this.salary = salary;
}
/**********************************************************
*
* StringBuilder的命名空间是System.Text
*
* 其中还显示了字符的输出格式如{0:C} 或者 {0,-20}
*
* *********************************************************/
public override string ToString()
{
StringBuilder sb = new StringBuilder(id.ToString(), 100);
sb.Append(": ");
sb.Append(string.Format("{0,-20}", name));
sb.Append(" ");
sb.Append(string.Format("{0:C}", salary));
return sb.ToString();
}
}
class EmployeeID
{
private readonly char prefix;
private readonly int number;
public EmployeeID(string id)
{
prefix = (id.ToUpper())[0];
number = int.Parse(id.Substring(1,3));
}
public override string ToString()
{
return prefix.ToString() + string.Format("{0,9:000}", number);
}
/**************************************************************
*
* 用作 Hashtable 中的键的对象必须实现或继承 Object.GetHashCode 和 Object.Equals 方法。
*
*
* ************************************************************/
public override int GetHashCode()
{
string str = this.ToString();
return str.GetHashCode();
}
public override bool Equals(object obj)
{
EmployeeID rhs = obj as EmployeeID;
if (rhs == null)
return false;
if (prefix == rhs.prefix && number == rhs.number)
return true;
return false;
}
}
}
18:IDisposable接口
using System;
using System.IO;
namespace Wrox.ProCSharp.AdvancedCSharp
{
class MainEntryPoint
{
static void Main()
{
string fileName;
Console.Write("Please type in the name of the file " +
"containing the names of the people to be cold-called > ");
fileName = Console.ReadLine();
ColdCallFileReader peopleToRing = new ColdCallFileReader();
try
{
peopleToRing.Open(fileName);
for (int i=0 ; i<peopleToRing.NPeopleToRing; i++)
{
peopleToRing.ProcessNextPerson();
}
Console.WriteLine("All callees processed correctly");
}
catch(FileNotFoundException e)
{
Console.WriteLine("The file {0} does not exist", fileName);
}
catch(ColdCallFileFormatException e)
{
Console.WriteLine(
"The file {0} appears to have been corrupted", fileName);
Console.WriteLine("Details of problem are: {0}", e.Message);
if (e.InnerException != null)
Console.WriteLine(
"Inner exception was: {0}", e.InnerException.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception occurred:/n" + e.Message);
}
finally
{
peopleToRing.Dispose();
}
Console.ReadLine();
}
}
/*****************************************************************************************
*
*
*class ColdCallFileReader :IDisposable
* .NET Framework 类库
IDisposable 接口
定义一种释放分配的非托管资源的方法。
有关此类型所有成员的列表,请参阅 IDisposable 成员。
[Visual Basic]
Public Interface IDisposable
[C#]
public interface IDisposable
[C++]
public __gc __interface IDisposable
[JScript]
public interface IDisposable
*
* 备注
使用此方法关闭或释放由实现此接口的类的实例保持的文件、流和句柄等非托管资源。根据约定,此方法用于与释放对象保持的资源或准备对象以便重新
使用有关的所有任务。
实现此方法时,对象必须通过在包容层次结构中传播调用来进行查找,以确保释放所有保持的资源。例如,如果对象 A 分配对象 B,而对象 B 又分配对象
C,那么 A 的 Dispose 实现必须对 B 调用 Dispose,而 B 反过来对 C 调用 Dispose。如果对象的基类实现了 IDisposable,对象还必须调用它们基类的
Dispose 方法。
如果某对象的 Dispose 方法被调用一次以上,则该对象必须忽略第一次调用后的所有调用。如果对象的 Dispose 方法被调用多次,对象不得引发异常。
如果由于资源已被释放且以前未调用 Dispose 而发生错误时,Dispose 会引发异常。
资源类型可能使用特定的约定来表示已分配状态和已释放状态。流类即是这样一种示例,传统上认为它们要么打开要么关闭。具有此类约定的类可能选
择实现带有自定义名称(如 Close)的公共方法,由该方法调用 Dispose 方法。
*
*
*
********************************************************************************************/
class ColdCallFileReader :IDisposable
{
FileStream fs;
StreamReader sr;
uint nPeopleToRing;
bool isDisposed = false;
bool isOpen = false;
public void Open(string fileName)
{
if (isDisposed)
throw new ObjectDisposedException("peopleToRing");
fs = new FileStream(fileName, FileMode.Open);
sr = new StreamReader(fs);
try
{
string firstLine = sr.ReadLine();
nPeopleToRing = uint.Parse(firstLine);
isOpen = true;
}
catch (FormatException e)
{
throw new ColdCallFileFormatException("First line isn/'t an integer", e);
}
}
public uint NPeopleToRing
{
get
{
if (isDisposed)
throw new ObjectDisposedException("peopleToRing");
if (!isOpen)
throw new UnexpectedException(
"Attempt to access cold call file that is not open");
return nPeopleToRing;
}
}
public void Dispose()
{
if (isDisposed)
return;
isDisposed = true;
isOpen = false;
if (fs != null)
{
fs.Close();
fs = null;
}
}
public void ProcessNextPerson()
{
if (isDisposed)
throw new ObjectDisposedException("peopleToRing");
if (!isOpen)
throw new UnexpectedException(
"Attempt to access cold call file that is not open");
try
{
string name;
name = sr.ReadLine();
if (name == null)
throw new ColdCallFileFormatException("Not enough names");
if (name[0] == 'Z')
{
throw new LandLineSpyFoundException(name);
}
Console.WriteLine(name);
}
catch(LandLineSpyFoundException e)
{
Console.WriteLine(e.Message);
}
finally
{
}
}
}
/*************************************************************************************
*
*
* 自己建立的异常类
*
****************************************************************************************/
class LandLineSpyFoundException : ApplicationException
{
public LandLineSpyFoundException(string spyName)
: base("LandLine spy found, with name " + spyName)
{
}
public LandLineSpyFoundException(string spyName, Exception innerException)
: base("LandLine spy found, with name " + spyName, innerException)
{
}
}
class ColdCallFileFormatException : ApplicationException
{
public ColdCallFileFormatException(string message)
: base(message)
{
}
public ColdCallFileFormatException(string message, Exception innerException)
: base(message, innerException)
{
}
}
class UnexpectedException : ApplicationException
{
public UnexpectedException(string message)
: base(message)
{
}
public UnexpectedException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=740185