前段时间在项目验收的过程中,验收人员提到了打开数据库使用完毕之后有没有及时关闭,然后就打开代码看了一眼,没有Close()方法呢。在检查过程中发现,虽然没有直接使用Close()方法,但在执行连接数据库时使用了using关键字,然后验收人员便说没有问题 。为什么没有使用Close()方法,仅有using关键字也是可以的呢?于是上网查了相关的资料,发现大家说的都是大同小异的,不清楚大家说的是不是都有道理,还有正确性如何。有那么一瞬间想到了纪老师提到的API文档,于是就想看看官方到底是如何解释的,来验证一下网上说的。下面是官方的解释:

The using keyword has three major uses:
三个主要的用法:
NO1:The using statement defines a scope at the end of which an object will be disposed.
NO2:The using directive creates an alias for a namespace or imports types defined in other namespaces.
NO3:The using static directive imports the members of a single class.

NO1:
Provides a convenient syntax that ensures the correct use of IDisposable objects.
Example:
The following example shows how to use the using statement.

using (var font1 = new Font("Arial", 10.0f))
{byte charset = font1.GdiCharSet;
}

Remarks
File and Font are examples of managed types that access unmanaged resources (in this case file handles and device contexts). There are many other kinds of unmanaged resources and class library types that encapsulate them. All such types must implement the IDisposable interface.

When the lifetime of an IDisposable object is limited to a single method, you should declare and instantiate it in the using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs within the using block. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler. The code example earlier expands to the following code at compile time (note the extra curly braces to create the limited scope for the object):

{var font1 = new Font("Arial", 10.0f);try{byte charset = font1.GdiCharSet;}finally{if (font1 != null)((IDisposable)font1).Dispose();}
}

For more information about the try-finally statement, see the try-finally topic.

Multiple instances of a type can be declared in the using statement, as shown in the following example:

using (var font3 = new Font("Arial", 10.0f),font4 = new Font("Arial", 10.0f))
{// Use font3 and font4.
}

You can instantiate the resource object and then pass the variable to the using statement, but this is not a best practice. In this case, after control leaves the using block, the object remains in scope but probably has no access to its unmanaged resources. In other words, it’s not fully initialized anymore. If you try to use the object outside the using block, you risk causing an exception to be thrown. For this reason, it’s generally better to instantiate the object in the using statement and limit its scope to the using block.

var font2 = new Font("Arial", 10.0f);
using (font2) // not recommended
{// use font2
}
// font2 is still in scope
// but the method call throws an exception
float f = font2.GetHeight();

NO2:
The using directive has three uses:
A.To allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace:

using System.Text;

B.To allow you to access static members and nested types of a type without having to qualify the access with the type name.

using static System.Math;

C.To create an alias for a namespace or a type. This is called a using alias directive.

using Project = PC.MyCompany.Project;

NO3:
The using static directive designates a type whose static members and nested types you can access without specifying a type name. Its syntax is:

using static <fully-qualified-type-name>;

where fully-qualified-type-name is the name of the type whose static members and nested types can be referenced without specifying a type name. If you do not provide a fully qualified type name (the full namespace name along with the type name), C# generates compiler error CS0246: “The type or namespace name ‘type/namespace’ could not be found (are you missing a using directive or an assembly reference?)”.

The using static directive applies to any type that has static members (or nested types), even if it also has instance members. However, instance members can only be invoked through the type instance.
Example:
The following example uses the using static directive to make the static members of the Console, Math, and String classes available without having to specify their type name.

using System;
using static System.Console;
using static System.Math;
using static System.String;class Program
{static void Main(){Write("Enter a circle's radius: ");var input = ReadLine();if (!IsNullOrEmpty(input) && double.TryParse(input, out var radius)) {var c = new Circle(radius);string s = "\nInformation about the circle:\n";s = s + Format("   Radius: {0:N2}\n", c.Radius);s = s + Format("   Diameter: {0:N2}\n", c.Diameter);s = s + Format("   Circumference: {0:N2}\n", c.Circumference);s = s + Format("   Area: {0:N2}\n", c.Area);WriteLine(s);}else {WriteLine("Invalid input...");}}
}public class Circle
{public Circle(double radius){Radius = radius;}public double Radius { get; set; }public double Diameter{get { return 2 * Radius; }}public double Circumference{get { return 2 * Radius * PI; }      }public double Area{get { return PI * Pow(Radius, 2); }}
}
// The example displays the following output:
//       Enter a circle's radius: 12.45
//
//       Information about the circle:
//          Radius: 12.45
//          Diameter: 24.90
//          Circumference: 78.23
//          Area: 486.95

In the example, the using static directive could also have been applied to the Double type. This would have made it possible to call the TryParse(String, Double) method without specifying a type name. However, this creates less readable code, since it becomes necessary to check the using static statements to determine which numeric type’s TryParse method is called.

上面内容就是API文档对using关键字的使用详细解释。查看文档后,验证了网友与官网的一致性。关于上面内容的中文理解,网上都是可以查到的哟。

C#中using关键字的使用相关推荐

  1. 【Java_基础】Java中Native关键字的作用

    本篇博文转载与:Java中Native关键字的作用 转载于:https://www.cnblogs.com/leiblog/p/10529056.html

  2. C/C++中extern关键字详解

    1 基本解释 :extern可以置于变量或者函数 前,以标示变量或者函数的定义在别的文件中 ,提示编译器遇到此变量和函数时在其他模块中寻找其定义 .此外extern也可用来进行链接指定. 也就是说ex ...

  3. C语言中的关键字详略

    首先我们要注意:在C语言中define不是关键字.define是编译器的预编译指令,是编译器实现的,不是C语言的内容. C语言编译器不认识#开头的东西,那些是预处理的事情. C编译器看到的是预处理完成 ...

  4. java中final关键字的使用

    final 中文翻译为 最终的,在java中也是较为常用的关键字之一. 在java 中 final 关键字可以修饰  类.方法.变量 final 修饰在类上,则表示该类不能被继承,如果里面的成员变量没 ...

  5. JavaScript中this关键字使用方法详解

    在面向对象编程语言中,对于this关键字我们是非常熟悉的.比如C++.C#和Java等都提供了这个关键字,虽然在开始学习的时候觉得比较难,但只要理解了,用起来是非常方便和意义确定的.JavaScrip ...

  6. C++中explicit关键字的作用

    C++中explicit关键字的作用 explicit用来防止由构造函数定义的隐式转换. 要明白它的作用,首先要了解隐式转换:可以用单个实参来调用的构造函数定义了从形参类型到该类类型的一个隐式转换. ...

  7. java 中关键字_Java中的关键字

    Java中的关键字一共有53个,包含常用的51个关键字和2个保留字 1.   保留字 2个:预留的关键字,即Java中未被使用到的关键字 const 保留字,即预留的关键字 goto 保留字,即预留的 ...

  8. java中的关键字static

    原文链接: https://zhuanlan.zhihu.com/p/70110497 昨晚面试中被问到,没能回答出来.这篇答疑文章写得非常好,无一字可增删,遂直接复制. 在平时开发当中,我们经常会遇 ...

  9. 在Oracle中exception关键字,Oracle表字段有Oracle关键字出现异常解决方案

    一.问题由来 现在进行项目改造,数据库需要迁移,由原来的使用GBase数据库改为使用Oracle数据库,今天测试人员在测试时后台报了一个异常. 把SQL语句单独复制出来进行查询,还是报错,仔细分析原因 ...

  10. 关于Oracle数据库19c中的关键字和保留字的说明

    关于Oracle数据库中的关键字和保留字的说明 官方文档节选: ​ You cannot use Oracle SQL reserved words as nonquoted identifiers. ...

最新文章

  1. C# 获取指定进程的主窗口句柄
  2. 不同服务器之间进行传输
  3. 演示FileInputStream案例演示
  4. 威佐夫博弈(模板题)
  5. Java和甜蜜的科学
  6. oracle全角字符转半角,Oracle 表字段全角字符轉換半角字符辦法
  7. SpaceX和美国宇航局计划明年4月向国际空间站发射Crew-4
  8. 【Spring笔记】Spring配置
  9. 在 Intellij IDEA 中 调试 angular e2e test
  10. 第一篇博客:WPF中 ScrollViewer控件的ScrollIntoView方法
  11. URLEncoder与URLDecoder
  12. 老毛子最想固件,支持打印机了
  13. 【计算机网络自顶向下方法】(哈工大)学习笔记
  14. 虚幻四C++入坑指南09:C++实现FPS游戏(3)Pitch Yaw Roll的作用 视角旋转 跳跃
  15. redis集群搭建及原理
  16. 嚼一嚼 class 文件结构
  17. 华捷艾米王亚楠:3D MR让未来无限可能
  18. POJ - 1849 Two(树的直径)
  19. java 通过User-Agent来判断是否是移动浏览器
  20. Ionic3项目实战

热门文章

  1. VS2010 无法计算HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0@VCTargetPath处的属性表达式...
  2. Linux下配置MySQL需要注意的几点
  3. connectionString加密
  4. Unix Shell 数学计算命令
  5. 小程序未来将有广阔的发展前景
  6. 大数据集群某节点彻底损毁后重装系统恢复(持续更新中)
  7. hive集群部署以及beeline和hive
  8. TypeError at / __init__() takes exactly 1 argument (2 given)
  9. 一句话讲清楚GIL锁
  10. No module named sipconfig