【IT168 技术文档】
栈语义和确定性的析构
C++经由栈语义模仿给了我们确定性的析构。简言之,栈语义是Dispose模式的良好的语法替代品。但是它在语义上比C# using块语法更直观些。请看下列的C#和C++代码段(都做一样的事情-连接两个文件的内容并把它写到第三个文件中)。
1) C#代码--使用块语义
public static void ConcatFilestoFile(String file1,
String file2, String outfile)
{
String str;
try{
using (StreamReader tr1 = new StreamReader(file1))
{
using (StreamReader tr2 = new StreamReader(file2))
{
using (StreamWriter sw = new StreamWriter(outfile))
{
while ((str = tr1.ReadLine()) != null)
sw.WriteLine(str);
while ((str = tr2.ReadLine()) != null)
sw.WriteLine(str);
}
}
}
}
catch (Exception e)
{ Console.WriteLine(e.Message); }
}
2) C++代码--栈语义
static void ConcatFilestoFile(String^ file1,
String^ file2, String^ outfile)
{
String^ str;
try{
StreamReader tr1(file1);
StreamReader tr2(file2);
StreamWriter sw(outfile);
while(str = tr1.ReadLine())
sw.WriteLine(str);
while(str = tr2.ReadLine())
sw.WriteLine(str);
}
catch(Exception^ e)
{ Console::WriteLine(e->Message); }
}
C#代码与相等的C++ 代码相比不仅免不了冗长,而且using块语法让程序员自己明确地指定他想在哪儿调用Dispose(using块的结束处),而使用C++/CLI的栈语义,只需让编译器使用常规的范围规则来处理它即可。事实上,这使得在C#中修改代码比在C++中更乏味-作为一实例,让我们修改这些代码以便即使仅存在一个输入文件也能创建输出文件。请看下面修改后的C#和C++代码。
3) 修改后的C#代码
public static void ConcatFilestoFile(String file1,
String file2, String outfile)
{
String str;
try{
using (StreamWriter sw = new StreamWriter(outfile))
{
try{
using (StreamReader tr1 = new StreamReader(file1))
{
while ((str = tr1.ReadLine()) != null)
sw.WriteLine(str);
}
}
catch (Exception) { }
using (StreamReader tr2 = new StreamReader(file2))
{
while ((str = tr2.ReadLine()) != null)
sw.WriteLine(str);
}
}
}
catch (Exception e){ }
}
把针对StreamWriter的using块放到顶层需要重新调整using块结构--这在上面情况下显然不是个大问题,但是对于实际开发中的修改,这可能是相当模糊的且易导致逻辑错误的。
4) 修改后的C++代码
static void ConcatFilestoFile(String^ file1,
String^ file2, String^ outfile)
{
String^ str;
try{
StreamWriter sw(outfile);
try{
StreamReader tr1(file1);
while(str = tr1.ReadLine())
sw.WriteLine(str);
}
catch(Exception^){}
StreamReader tr2(file2);
while(str = tr2.ReadLine())
sw.WriteLine(str);
}
catch(Exception^){}
}