C#中using的用法

1.前言

遇到过很多次using,但对于using到底有哪些用法一直没有去了解过,通过学习,了解到using的三种用法,下面一一介绍

2.using的三种用法

1.using指令

使用using导入命名空间,这是一种最常见的用法了。using + 命名空间名字,这样可以在程序中直接用命令空间中的类型,而不必指定类型的详细命名空间

如:using System;

2.using别名

using + 别名 = 包括详细命名空间信息的具体的类型

使用它主要是可能两个命名空间中可能有相同名字的类型,在调用时就要详细写明是哪个命名空间以便区分这些相同名字的类型,比较麻烦;用别名的方法会更简洁,用到哪个类就给哪个类做别名声明就可以了。注意:并不是说两个名字重复,给其中一个用了别名,另外一个就不需要用别名了,如果两个都要使用,则两个都需要用using来定义别名的。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Test1 = Achunchun.test;
using Test2 = Bchunchun.test;

namespace KGgraphStructure
{
   public class Program
    {
       static void Main(string[] args)
       {
           Test1.method();
           Test2.method();
           Console.ReadKey();
       }
    }
}
namespace Achunchun
{
    public class test
    {
        public static void method()
        {
            Console.WriteLine("你好");
        }
    }
}

namespace Bchunchun
{
    public class test
    {
        public static void method()
        {
            Console.WriteLine("你好");
        }
    }
}

3.using语句

是用来简化资源释放的,在一定的范围内有效,using则是定义一个范围,一旦出了这个范围,自动调用IDisposable释放掉该对象资源,但是并不是所有对象都能使用using语句,只有实现了IDisposable接口的类才可以使用,禁止为不支持IDisposable接口的类型使用using语句,否则会出现编译错误。

using语句的使用

1.在using语句之前声明对象


SqlConnection conn=new SqlConnection(connString)  
using(conn)
{
  //content
}

2.在using语句之中声明对象

SqlConnection conn=new SqlConnection(connString)
{
   //content
}

3.可以有多个对象与 using 语句一起使用,但是必须在 using 语句内部声明这些对象

using (Font font3=new Font("Arial",10.0f), font4=new Font("Arial",10.0f))
      {
          // content
      }

使用规则:

1.using只能用于实现了IDisposable接口的类型,禁止为不支持IDisposable接口的类型使用using语句,否则会出现编译错误;
2.using语句适用于清理单个非托管资源的情况,而多个非托管对象的清理最好以try-finnaly来实现,因为嵌套的using语句可能存在隐藏的Bug。内层using块引发异常时,将不能释放外层using块的对象资源;
3.using语句支持初始化多个变量,但前提是这些变量的类型必须相同,例如:
        

using(Pen p1 = new Pen(Brushes.Black), p2 = new Pen(Brushes.Blue))
      {
          //
      }


4.针对初始化多个不同类型的变量时,可以都声明为IDisposable类型,例如:
       

 using (IDisposable font = new Font("Verdana", 12), pen = new Pen(Brushes.Black))
      {
          float size = (font as Font).Size;
          Brush brush = (pen as Pen).Brush;
      }

using实质
    在程序编译阶段,编译器会自动将using语句生成为try-finally语句,并在finally块中调用对象的Dispose方法,来清理资源。所以,using语句等效于try-finally语句,例如:

using (Font f2 = new Font("Arial", 10, FontStyle.Bold))
{
     font2.F();
}

被编译器翻译为:
    

 Font f2 = new Font("Arial", 10, FontStyle.Bold);
  try
  {
      font2.F();

  }
  finally
  {
      if (f2 != null) ((IDisposable)f2).Dispose();
  }

参考:

https://www.cnblogs.com/stroll/p/8967319.html

https://www.cnblogs.com/hanke123/p/5968824.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值