111,120
社区成员
发帖
与我相关
我的任务
分享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 (Exception e)
{
Console.WriteLine("Exception occurred:\n" + e.Message);
}
finally
{
peopleToRing.Dispose(); // 关闭已打开的文件
}
Console.ReadLine();
}
}
class ColdCallFileReader : IDisposable // 继承接口IDisposable, 确保正确释放对象
{
FileStream fs; // 专用于连接文件
StreamReader sr; // 专用于读取文本文件
uint nPeopleToRing;
bool isDisposed = false;
bool isOpen = false;
public void Open(string fileName)
{
if (isDisposed) // 检查在删除对象后, 客户机代码是否不正确地调用了它
throw new Exception("peopleToRing");
fs = new FileStream(fileName, FileMode.Open);
sr = new StreamReader(fs);
string firstLine = sr.ReadLine();
nPeopleToRing = uint.Parse(firstLine);
isOpen = true;
}
public uint NPeopleToRing // 返回文件中假定的人数
{
get
{
if (isDisposed)
throw new Exception("peopleToRing");
if (!isOpen)
throw new Exception("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 Exception("peopleToRing");
if (!isOpen) throw new Exception("Attempt to access cold call file that is not open");
string name;
name = sr.ReadLine();
if (name == null) // 如果到达文件末尾, 抛出异常
throw new Exception("Not enough names");
Console.WriteLine(name);
}
}
}