using 指令簡化型別名稱namespace CSharpStation
{
class NamespaceCSS
{
public static void Main()
{
Console.WriteLine("This is the new C# Station Namespace.");
}
}
}
兩種寫法等價:
// 寫法 1:巢狀區塊
namespace CSharpStation
{
namespace Tutorial
{
class MyClass { }
}
}
// 寫法 2:點號串接 (較簡潔)
namespace CSharpStation.Tutorial
{
class MyClass { }
}
建議以層次結構組織:公司.產品.模組.功能。
namespace CSharpStation
{
namespace Tutorial
{
class MyExample1
{
public static void MyPrint1() => Console.WriteLine("First example.");
}
}
class NamespaceCalling
{
public static void Main()
{
// 同層命名空間可用相對名稱
Tutorial.MyExample1.MyPrint1();
// 外部命名空間需完整名稱
CSharpStation.Tutorial.MyExample2.MyPrint2();
}
}
}
// 同一邏輯命名空間可分散在多檔案
namespace CSharpStation.Tutorial
{
class MyExample2
{
public static void MyPrint2() => Console.WriteLine("Second example.");
}
}
using System; // 匯入 System
using CSharpStation.Tutorial; // 匯入巢狀命名空間
class UsingDirective
{
public static void Main()
{
MyExample.MyPrint(); // 直接使用型別名稱
}
}
namespace CSharpStation.Tutorial
{
class MyExample
{
public static void MyPrint() => Console.WriteLine("Using directive example.");
}
}
using System;
using CsTut = CSharpStation.Tutorial.MyExample; // 別名
class AliasDirective
{
public static void Main()
{
CsTut.MyPrint(); // 呼叫 MyExample.MyPrint
MyPrint(); // 呼叫本類別的 MyPrint
}
static void MyPrint() => Console.WriteLine("Local method.");
}
// 若無別名,改用 using CSharpStation.Tutorial.MyExample
// 則 MyPrint() 模稜兩可,編譯錯誤
class)struct)interface)enum)delegate)namespace,與專案預設命名空間一致。.Internal 或 .Impl 子命名空間。