首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 命名空間完整指南:定義、巢狀、using 指令、別名、成員類型

     編輯:關於C語言

學習目標

  1. 理解命名空間組織程式碼、避免衝突的作用
  2. 定義與巢狀命名空間
  3. 使用 using 指令簡化型別名稱
  4. 使用別名解決同名衝突
  5. 掌握命名空間可包含的成員類型

基本定義

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 指令

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)

最佳實務

  1. 每個原始檔頂端宣告 namespace,與專案預設命名空間一致。
  2. 資料夾結構對應命名空間層次。
  3. 公開 API 型別放在穩定、有意義的命名空間。
  4. 內部實作型別放在 .Internal 或 .Impl 子命名空間。
  5. 避免過深巢狀 (建議 ≤ 4 層)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved