C#中using关键字的作用
2012-07-02 09:34
369 查看
C#中using有两种作用。1、作为指令,用于引用命名空间的,如using System.IO;
2、作为语句,using定义一个范围,在退出using之后,在此范围末尾之后便自动释放对象,起到了自动释放资源的作用。如下面笔者使用StreamWriter列的WriteLine方法先向指定文本文件写入数据,然后调用streamReader的ReadToEnd方法从刚刚指定的文本文件中读取数据。当使用using语句时,首先系统先为使用using的代码块分配资源,在出了using代码块后因为使用using语句,所以刚刚为代码块分配的资源就会自动释放,主要就起到了自动资源释放的作用,减少系统开销。
static void Main(string[] args)
{
string strFile = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\Test.txt";
//指定在当前路径下的Test.txt
try
{
//检查文件是否存在,如果存在先删除,给指定的文本文件赋予新的内容
if (File.Exists(strFile))
{
File.Delete(strFile);
}
//实例化StreamWriter,并写入数据到文本文件
using (StreamWriter sw = new StreamWriter(strFile))
{
sw.WriteLine("老当益壮,宁移白首之心!");
sw.WriteLine("穷且益坚,不坠青云之志!");
}
//实例化StreamReader,并使用ReadToEnd方法从文本文件中从头到尾读取数据并输出
using (StreamReader sr = new StreamReader(strFile))
{
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
2、作为语句,using定义一个范围,在退出using之后,在此范围末尾之后便自动释放对象,起到了自动释放资源的作用。如下面笔者使用StreamWriter列的WriteLine方法先向指定文本文件写入数据,然后调用streamReader的ReadToEnd方法从刚刚指定的文本文件中读取数据。当使用using语句时,首先系统先为使用using的代码块分配资源,在出了using代码块后因为使用using语句,所以刚刚为代码块分配的资源就会自动释放,主要就起到了自动资源释放的作用,减少系统开销。
static void Main(string[] args)
{
string strFile = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\Test.txt";
//指定在当前路径下的Test.txt
try
{
//检查文件是否存在,如果存在先删除,给指定的文本文件赋予新的内容
if (File.Exists(strFile))
{
File.Delete(strFile);
}
//实例化StreamWriter,并写入数据到文本文件
using (StreamWriter sw = new StreamWriter(strFile))
{
sw.WriteLine("老当益壮,宁移白首之心!");
sw.WriteLine("穷且益坚,不坠青云之志!");
}
//实例化StreamReader,并使用ReadToEnd方法从文本文件中从头到尾读取数据并输出
using (StreamReader sr = new StreamReader(strFile))
{
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
相关文章推荐
- C#中using关键字的作用及用法
- C#中using关键字的作用及用法
- C#中using关键字的作用及用法
- C#中using关键字的作用及其用法
- C#中using关键字的作用及其用法(转)
- C#中using关键字的作用及其用法
- C#中using关键字的作用及其用法
- 【转】C#中using关键字的作用及用法
- C#中using关键字的作用及其用法
- C#中using关键字的作用及其用法
- C#中的using关键字
- C#中using关键字的使用
- c# using的作用
- C#中params关键字的作用理解
- C#中params关键字的作用理解
- C# 关键字--using用法[转]
- C# using作用透析
- NET面试题:C#中的lock关键字有何作用
- c# using 关键字小结
- 关于C#中params关键字的作用及用法