C# using的三種用法


一、using指令

  在文件頂部引用命名空間,如:using System;

二、using別名

  為命名空間或類型定義別名,這種做法有個好處就是當同一個cs文件引用了兩個不同的命名空間,但是兩個命名空間都包括了一個相同名字的類型的時候,就會為此類型命名空間創建別名。

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;
        }
    }
}

三.using語句

定義一個范圍,在范圍結束時處理對象。using語句提供了一個脈絡清晰的機制來控制資源的生存期,創建的對象會在using語句結束時被摧毀,使用前提該對象必須繼承了IDisposable接口。某些類型的非托管對象有數量限制或很耗費系統資源,在代碼使用完它們后,盡可能快的釋放它們時非常重要的。using語句有助於簡化該過程並確保這些資源被適當的處置(dispose)。

它有兩種使用形式。

1.using (ResourceType Identifier = Expression ) Statement

 圓括號中的代碼分配資源,Statement是使用資源的代碼

 using語句會隱式產生處置該資源的代碼,其步驟為:

 a:分配資源

 b:把Statement放進tyr塊

 c:創建資源的Dispose方法的調用,並把它放進finally塊,例如:

using System;
using System.IO;

namespace @using
{
    class Program
    {
        static void Main(string[] args)
        {
            using (TextWriter tw = File.CreateText("test.txt"))
            {
                tw.Write("this is a test");
            }
           
            using (TextReader tr = File.OpenText("test.txt"))
            {
                string input;
                while ((input = tr.ReadLine()) != null)
                {
                    Console.WriteLine(input);
                }
            }
            Console.ReadKey();
        }
    }
}

輸出:this is a test

 

2.using (Expression)  Statement

Expression 表示資源,Statement是使用資源,資源需要在using之前聲明

TextWriter tw = File.CreateText("test.txt");
using(tw){......}

這種方式雖然可以確保對資源使用結束后調用Dispose方法,但不能防止在using語句已經釋放了他的非托管資源之后使用該資源,可能導致不一致的狀態,不推薦使用。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM