C# using的用法

來源:互聯網
上載者:User

標籤:結束   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的用法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.