W3Cschool
恭喜您成為首批注冊用戶
獲得88經驗值獎勵
命名空間(namespace) 專為提供一種來保留一套獨立名字與其他命名區(qū)分開來的方式。一個命名空間中聲明的類的名字與在另一個命名空間中聲明的相同的類名并不會發(fā)生沖突。
命名空間的定義以關鍵字 namespace 開始,其后跟命名空間的名稱:
namespace namespace_name
{
// 代碼聲明
}
調用的函數或變量的命名空間啟用版本,在命名空間名稱如下:
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í)行上述代碼,得到如下結果:
Inside first_space
Inside second_space
關鍵詞 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í)行上述代碼,得到如下結果:
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í)行上述代碼,得到如下結果:
Inside first_space
Inside second_space
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: