?
前言
说起 C# using 语句, 想必大家都不陌生, 它是 C# 中关键字之一我们基本每天写代码都会使用到, 其实也非常简单
1.
首先, 说说 using 有哪些用途
1)
用于引用其他程序集中的命名空间, 例如:
- using System.Collections.Generic;
- 2)
为命名空间或类名设置别名
1)
为命名空间设置别名
- using Gen = System.Collections.Generic;
- 2)
为类名设置别名
- using IntList = System.Collections.Generic.List<int>;
- IntList list = new IntList();
- list.Add(1);
- 3)
释放对象资源
1)
释放对象资源也是 using 常见用法之一, C# 通过 .NET Framework 公共语言运行库 (CLR) 自动释放用于存储不再需要的对象的内存
2)
使用 using 释放对象资源的类, 必须实现 System.IDisposable 接口, 在 Dispose() 方法中完成对资源的释放
2.
using 基本用法
首先, 申明一个测试类
- public
- class UsingClass : System.
- IDisposable
- {
- public string ObjectName { get; set
- ; }
- public UsingClass(string
- objName)
- {
- this.ObjectName = objName;
- }
- public void
- Dispose()
- {
- Console.WriteLine("{0} 已经销毁"
- , ObjectName);
- }
- }
- 1)
声明一个对象
- using (UsingClass uc = new UsingClass("对象"))
- {
- Console.WriteLine("using 语句执行");
- }
执行结果:
2)
同时声明多个对象
- using (UsingClass uca = new UsingClass("对象 A"), ucb = new UsingClass("对象 B"), ucc = new UsingClass("对象 C"))
- {
- Console.WriteLine("using 语句执行");
- }
执行结果:
3)
new 一个对象 (当然这种用法没什么实际意义)
- using (new UsingClass("对象"))
- {
- Console.WriteLine("using 语句执行");
- }
执行结果:
来源: http://www.bubuko.com/infodetail-2542381.html