[C#基础知识]using的使用

时间:2021-12-14 03:55:21

1.在文件顶部引用命名空间,如:using System;

2.为命名空间或类型定义别名;

  如果命名空间过长,键入时会比较麻烦,如果该命名空间会在代码中多次调用的话,那么为命名空间定义别名,是比较明智的选择,并且还能够避免类名冲突!是不是很机智啊?!

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; //为命名空间定义别名 "ElseName" using ElseName = This.Is.Very.Very.Long.NamespaceName; //为类定义定义别名 using ElseCName = This.Is.Very.Very.Long.NamespaceName.ThisIsVeryVeryLongClassName; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //通过别名实例化对象 ::是命名空间别名的修饰符 ElseName::NamespaceExample NSEx = new ElseName::NamespaceExample(); //通过别名实例化对象 ElseCName CN = new ElseCName(); Response.Write("命名空间:" + NSEx.GetNamespace() + ";类名:" + CN.GetClassName()); } } namespace This.Is.Very.Very.Long.NamespaceName { class NamespaceExample { public string GetNamespace() { return this.GetType().Namespace; } } class ThisIsVeryVeryLongClassName { public string GetClassName() { return System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName; } } }

3.使用using,定义范围,在该范围结束时回收资源。

  注意使用前提:该对象必须继承了IDisposable接口,功能等同于try{}Finally{}。

string str = "LittleBai"; //创建写入字符串 Byte[] bytesToWrite = Encoding.Default.GetBytes(str); ; //创建文件 using (FileStream fs = new FileStream("test.txt", FileMode.Create)) { //将字符串写入文件 fs.Write(bytesToWrite, 0, bytesToWrite.Length); }

  执行完成后,程序会自动回收资源!