標籤:結束 rgs encoding finally log 定義 space classname current
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{}catch{}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);}
執行完成後,程式會自動回收資源!
交流群:225443677
C# using的用法