:: 運算子 (C# 參考):: operator (C# reference)

使用命名空間別名辨識符號 :: 來存取別名命名空間的成員。Use the namespace alias qualifier :: to access a member of an aliased namespace. 您只能在 :: 兩個識別碼之間使用限定詞。You can use the :: qualifier only between two identifiers. 左邊的識別碼可以是下列任何別名:The left-hand identifier can be any of the following aliases:

  • 使用 using alias指示詞建立的命名空間別名:A namespace alias created with a using alias directive:

    using forwinforms = System.Drawing;
    using forwpf = System.Windows;
    
    public class Converters
    {
        public static forwpf::Point Convert(forwinforms::Point point) => new forwpf::Point(point.X, point.Y);
    }
    
  • 外部別名An extern alias.

  • global 別名,這是全域命名空間別名。The global alias, which is the global namespace alias. 全域命名空間是包含未在具名命名空間中宣告之命名空間和型別的命名空間。The global namespace is the namespace that contains namespaces and types that are not declared inside a named namespace. :: 限定詞搭配使用時,global 別名一律會參考全域命名空間,即使有使用者定義的 global 命名空間別名也一樣。When used with the :: qualifier, the global alias always references the global namespace, even if there is the user-defined global namespace alias.

    下列範例使用 global 別名來存取 .NET System 命名空間,這是全域命名空間的成員。The following example uses the global alias to access the .NET System namespace, which is a member of the global namespace. 如果沒有 global 別名,則會存取使用者定義的 System 命名空間,這是 MyCompany.MyProduct 命名空間的成員:Without the global alias, the user-defined System namespace, which is a member of the MyCompany.MyProduct namespace, would be accessed:

    namespace MyCompany.MyProduct.System
    {
        class Program
        {
            static void Main() => global::System.Console.WriteLine("Using global alias");
        }
    
        class Console
        {
            string Suggestion => "Consider renaming this class";
        }
    }
    

    注意

    global 關鍵字只有在它是 :: 限定詞的左邊識別碼時,才是全域命名空間別名。The global keyword is the global namespace alias only when it's the left-hand identifier of the :: qualifier.

您也可以使用 . 權杖來存取別名命名空間的成員。You can also use the . token to access a member of an aliased namespace. 不過, . 標記也用來存取類型成員。However, the . token is also used to access a type member. :: 限定詞可確保其左邊的識別碼一律會參考命名空間別名,即使存在具有相同名稱的型別或命名空間也一樣。The :: qualifier ensures that its left-hand identifier always references a namespace alias, even if there exists a type or namespace with the same name.

C# 語言規格C# language specification

如需詳細資訊,請參閱 C# 語言規格命名空間別名限定詞一節。For more information, see the Namespace alias qualifiers section of the C# language specification.

另請參閱See also