鍍金池/ 教程/ C#/ 命名空間
循環(huán)
正則表達式
概述
委托
多態(tài)性
字符串
繼承
結(jié)構(gòu)體
集合
變量
不安全代碼
判斷
反射
異常處理
可空類型
方法
數(shù)據(jù)類型
命名空間
文件 I/O
類型轉(zhuǎn)換
屬性
程序結(jié)構(gòu)
事件
接口
預(yù)處理指令
運算符
多線程
匿名方法
索引器
泛型
封裝
常量和文字
基本語法
特性
數(shù)組
環(huán)境配置
運算符重載
枚舉

命名空間

命名空間(namespace) 專為提供一種來保留一套獨立名字與其他命名區(qū)分開來的方式。一個命名空間中聲明的類的名字與在另一個命名空間中聲明的相同的類名并不會發(fā)生沖突。

命名空間的定義

命名空間的定義以關(guān)鍵字 namespace 開始,其后跟命名空間的名稱:

namespace namespace_name
{
   // 代碼聲明
}

調(diào)用的函數(shù)或變量的命名空間啟用版本,在命名空間名稱如下:

namespace_name.item_name;

下面的程序演示了命名空間的使用:

using System;
namespace first_space
{
   class namespace_cl
   {
      public void func()
      {
         Console.WriteLine("Inside first_space");
      }
   }
}

namespace second_space
{
   class namespace_cl
   {
      public void func()
      {
         Console.WriteLine("Inside second_space");
      }
   }
}

class TestClass
{
   static void Main(string[] args)
   {
      first_space.namespace_cl fc = new first_space.namespace_cl();
      second_space.namespace_cl sc = new second_space.namespace_cl();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

編譯執(zhí)行上述代碼,得到如下結(jié)果:

Inside first_space
Inside second_space

關(guān)鍵字 using

關(guān)鍵詞 using 指出了該程序是在使用給定的命名空間的名稱。例如,我們在程序中使用的是系統(tǒng)命名空間。其中有 Console 類的定義。我們只需要寫:

Console.WriteLine ("Hello there");

我們還可以寫完全限定名稱:

System.Console.WriteLine("Hello there");

你也可以使用 using 指令避免還要在前面加上 namespace 。這個指令會告訴編譯器后面的代碼使用的是在指定的命名空間中的名字。命名空間是因此包含下面的代碼:

讓我們重寫前面的示例,使用 using 指令:

using System;
using first_space;
using second_space;

namespace first_space
{
   class abc
   {
      public void func()
      {
         Console.WriteLine("Inside first_space");
      }
   }
}

namespace second_space
{
   class efg
   {
      public void func()
      {
         Console.WriteLine("Inside second_space");
      }
   }
}   

class TestClass
{
   static void Main(string[] args)
   {
      abc fc = new abc();
      efg sc = new efg();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

編譯執(zhí)行上述代碼,得到如下結(jié)果:

Inside first_space
Inside second_space

嵌套命名空間

你可以在一個命名空間中定義另一個命名空間,方法如下:

namespace namespace_name1
{
   // 代碼聲明
   namespace namespace_name2
   {
    //代碼聲明
   }
}

你可以使用點運算符“.”來訪問嵌套命名空間中的成員

using System;
using first_space;
using first_space.second_space;

namespace first_space
{
   class abc
   {
      public void func()
      {
         Console.WriteLine("Inside first_space");
      }
   }
   namespace second_space
   {
      class efg
      {
         public void func()
         {
            Console.WriteLine("Inside second_space");
         }
      }
   }   
}

class TestClass
{
   static void Main(string[] args)
   {
      abc fc = new abc();
      efg sc = new efg();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

編譯執(zhí)行上述代碼,得到如下結(jié)果:

Inside first_space
Inside second_space
上一篇:運算符下一篇:循環(huán)