7 using语句

using 语句

using语句不是using指令 using指令后面讲解

某些类型的非托管对象有数量限制或很耗费系统资源,在用完他们,尽可能的释放他们是非常重要的。

using语句由助于简化该过程并确保这些资源被适当处理

资源是指一个实现了 System.IDisposable接口的类或结构,接口含有一个单独的Dispose方法

使用资源的阶段由以下几部分组成

  • 分配资源
  • 使用资源
  • 处置资源

如果在正在使用资源的那部分代码中产生一个意外错误,那么处置资源的代码可能得不到执行

// 分配资源
ResType Resource = new ResType();

// 使用资源
// 使用Resource的语句 如果在这一步发送异常 Dispose将不会调用

// 处置资源
Resource.Dispose();

资源的包装和使用

​ using语句帮助减少意外的运行时错误带来的潜在问题,他整洁的包装了资源的使用。

​ 有两种形式的using语句,第一种如下:

  • 圆括号内的代码分配资源
  • Statement是 使用资源的代码
  • using语句隐示参数处置该资源的代码
// 				分配资源				   使用资源
using(ResourceType Identifier = Expression)Statement
public class ResType : IDisposable
{
    public void Dispose()
    {
        
    }

    public void xxx()
    {
        Console.WriteLine("hello");
    }
}

internal class Program
{
    private static void Main(string[] args)
    {
        using (ResType Resource = new ResType())
        {
            Resource.xxx();
        };     
    }
}

image-20221028134517020

using语句的实例

​ 下面的代码使用using语句两次,一次对名称为TextWriter的类,一次对名称为TextReader的类,他们都来自System.IO 命名控件,两个类都实现了IDidposable接口,这是using语句的要求

  • TextWriter资源打开一个文本文件,并向文件写入一行
  • TextReader资源接着打开相同的文本文件,一行一行的读取并显示他的内容
  • 在两种情况中,using语句确保代用对象的Dispose方法
  • 还要注意Main中的Using语句和开始两行using指令的区别
using System;
using System.IO;	// using指令 不是using语句
namespace _03_using语句
{
    /*
	*┌────────────────────────────────────────────────┐
	*│ 描    述:Class1                                                    
	*│ 作    者:龙绍进                                              
	*│ 版    本:1.0                                              
	*│ 创建时间:2022/10/28 13:51:36                        
	*└────────────────────────────────────────────────┘
	*/
    internal class Class1
    {
		static void Main()
		{
			// using语句
			using (TextWriter tw = File.CreateText("Lincoln.txt"))
			{
				tw.WriteLine("Four score and seven years ago, ...");
			}

			// using语句
			using (TextReader tr = File.OpenText("Lincoln.txt"))
			{
				string InputString;
				while(null != (InputString = tr.ReadLine()))
					Console.WriteLine(InputString);
			}
		}
    }
}

多个资源和嵌套

using语句还可以用于相同类型的多个资源,资源用逗号隔开,语法如下:

using(ResourceType Id1 = Expr1, Id2 = Expr2,...) EmbeddedStatement

例如,下面代码中,每个using语句分配并使用两个资源

using (TextWriter tw = File.CreateText("Lincoln.txt"), tw2 = File.CreateText("two.txt"))
{
    tw.WriteLine("one");
    tw2.WriteLine("two");
}
using (TextReader tr = File.OpenText("Lincoln.txt"), tr2 = File.OpenText("two.txt"))
{
    string res;
    while(null != (res = tr.ReadLine()))
        Console.WriteLine(res);
    while (null != (res = tr2.ReadLine()))
        Console.WriteLine(res);
}

using语句还可以嵌套

using (TextWriter tw = File.CreateText("Lincoln.txt"))
{
    tw.WriteLine("one");
    // 嵌套语句
    using (TextWriter tw2 = File.CreateText("two.txt"))
    {
        tw2.WriteLine("two");
    }
}

using语句的另外一种形式

using语句的另一种形式如下:

using (资源) 使用资源

在这种形式中,资源在using语句之前声明。

TextWriter tw = Fiel.CreateText("hello.txt");
using (tw)
{
	tw.Writeline("hello");
}
// 不推荐使用 因为可能在tw已经被释放了 然后using使用该资源,导致不一致的状态

image-20221028141635660

其他语句

image-20221028141843437

checked unchecked 控制溢出检查上下文

foreach 遍历一个集合的每个成员

try throw finally 处理异常

return 将控制返回到调佣函数的成员,而且还能返回一个值

yield 用于迭代

posted @ 2022-10-29 00:07  LD_Dragon_sky  阅读(28)  评论(0编辑  收藏  举报