天天學C#- using

來源:互聯網
上載者:User

   學c#的都知道,using指令可以用於引用命名空間,如:
   using System;

   也可以來指定命名空間或類的別名,如:
 // 摘錄MSDN
// cs_using_directive.cs
using MyAlias = MyCompany.Proj.Nested;  // define an alias to represent a namespace

namespace MyCompany.Proj
{
   public class MyClass
   {
      public static void DoNothing()
      {
      }
   }

   namespace Nested   // a nested namespace
   {
      public class ClassInNestedNameSpace
      {
         public static void SayHello()
         {
            System.Console.WriteLine("Hello");
         }
      }
   }

}

public class UnNestedClass
{
   public static void Main()
   {
      MyAlias.ClassInNestedNameSpace.SayHello();   // using alias
   }
}

也可以用來指定類的別名:

// cs_using_directive2.cs
using System;   // using directive
using AliasToMyClass = NameSpace1.MyClass;   // using alias for a class

namespace NameSpace1
{
   public class MyClass
   {
      public override string ToString()
      {
         return "You are in NameSpace1.MyClass";
      }
   }
}

namespace NameSpace2
{
   class MyClass
   {
   }
}

namespace NameSpace3
{
   using NameSpace1;   // using directive
   using NameSpace2;   // using directive

   class Test
   {
      public static void Main()
      {
         AliasToMyClass somevar = new AliasToMyClass();
         Console.WriteLine(somevar);
      }
   }
}

今天學到的是using語句,聽說過的就不用往下看了,沒聽過的可以看看
using語句的基本用法
using(some instances)
{
        //using these instances
}//dispose these instances by compiler
括弧中包含{}中引用的執行個體,在退出using語句後,這些對象被回收(dispose)

樣本:
using System.Drawing;
class a
{
   public static void Main()
   {
      using (Font MyFont = new Font("Arial", 10.0f), MyFont2 = new Font("Arial", 10.0f))
      {
         // use MyFont and MyFont2
      }   // compiler will call Dispose on MyFont and MyFont2

      Font MyFont3 = new Font("Arial", 10.0f);
      using (MyFont3)
      {
         // use MyFont3
      }   // compiler will call Dispose on MyFont3

   }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.