命名空間

namespace 關鍵字用來宣告包含一組相關物件的範圍。 您可以使用命名空間來組織程式碼項目,並建立全域唯一的型別。

namespace SampleNamespace
{
    class SampleClass { }

    interface ISampleInterface { }

    struct SampleStruct { }

    enum SampleEnum { a, b }

    delegate void SampleDelegate(int i);

    namespace Nested
    {
        class SampleClass2 { }
    }
}

「檔案範圍的命名空間宣告」可讓您宣告檔案中的所有類型都會位於單一命名空間中。 檔案範圍的命名空間宣告適用於 C# 10。 下列範例與上一個範例類似,但使用檔案範圍的命名空間宣告:

using System;

namespace SampleFileScopedNamespace;

class SampleClass { }

interface ISampleInterface { }

struct SampleStruct { }

enum SampleEnum { a, b }

delegate void SampleDelegate(int i);

上述範例未包含巢狀命名空間。 檔案範圍的命名空間不能包含其他命名空間宣告。 您無法宣告巢狀命名空間或第二個檔案範圍的命名空間:

namespace SampleNamespace;

class AnotherSampleClass
{
    public void AnotherSampleMethod()
    {
        System.Console.WriteLine(
            "SampleMethod inside SampleNamespace");
    }
}

namespace AnotherNamespace; // Not allowed!

namespace ANestedNamespace // Not allowed!
{
   // declarations...
}

在命名空間內,您可以宣告下列一或多個類型:

編譯器會新增預設命名空間。 這個未命名的命名空間,有時候是指全域命名空間,會出現在每個檔案中。 它包含未包含在宣告命名空間中的宣告。 全域命名空間中的任何識別項都可用於具名命名空間中。

命名空間會隱含地具有公用存取權。 如需可在命名空間中指派給項目之存取修飾詞的討論,請參閱存取修飾詞

您可在兩個或多個宣告中定義命名空間。 例如,下例會將兩個類別定義為 MyCompany 命名空間的一部分︰

namespace MyCompany.Proj1
{
    class MyClass
    {
    }
}

namespace MyCompany.Proj1
{
    class MyClass1
    {
    }
}

下例顯示如何在巢狀命名空間中呼叫靜態方法。

namespace SomeNameSpace
{
    public class MyClass
    {
        static void Main()
        {
            Nested.NestedNameSpaceClass.SayHello();
        }
    }

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

C# 語言規格

如需詳細資訊,請參閱 C# 語言規格命名空間一節。 如需檔案範圍的命名空間宣告詳細資訊,請參閱功能規格

另請參閱