방법: 네임스페이스 별칭 한정자 사용(C# 프로그래밍 가이드)

업데이트: 2007년 11월

전역 네임스페이스의 멤버에 액세스할 수 있다는 점은 멤버가 이름이 동일한 다른 엔터티에 의해 숨겨질 수 있는 경우에 유용합니다.

예를 들어, 다음 코드에서 Console은 System 네임스페이스의 Console 형식 대신 TestApp.Console로 해석됩니다.

using System;
class TestApp
{
    // Define a new class called 'System' to cause problems.
    public class System { }

    // Define a constant called 'Console' to cause more problems.
    const int Console = 7;
    const int number = 66;

    static void Main()
    {
        // Error  Accesses TestApp.Console
        //Console.WriteLine(number);
    }
}

System 네임스페이스가 TestApp.System 클래스에 의해 숨겨져 있으므로 System.Console을 사용해도 여전히 오류가 발생합니다.

// Error  Accesses TestApp.System
System.Console.WriteLine(number);

그러나 다음과 같이 global::System.Console을 사용하여 이 오류를 해결할 수 있습니다.

// OK
global::System.Console.WriteLine(number);

왼쪽 식별자가 global이면 오른쪽 식별자에 대한 검색이 전역 네임스페이스에서 시작됩니다. 예를 들어, 다음 선언에서는 TestApp를 전역 공간의 멤버로 참조합니다.

class TestClass : global::TestApp

System이라는 자체 네임스페이스는 만들지 않는 것이 좋으며, 이러한 네임스페이스를 만드는 코드는 거의 찾아볼 수 없습니다. 그러나 보다 큰 프로젝트에서는 여러 가지 형태의 네임스페이스 중복이 발생할 수 있습니다. 이러한 경우 전역 네임스페이스 한정자를 사용하면 확실하게 루트 네임스페이스를 지정할 수 있습니다.

예제

이 예제에서는 TestClass 클래스가 System 네임스페이스에 포함되므로 System 네임스페이스에 의해 숨겨져 있는 System.Console 클래스를 참조하려면 global::System.Console을 사용해야 합니다. 또한 System.Collections 네임스페이스를 참조하기 위해 별칭 colAlias가 사용되고 있으므로 System.Collections.Hashtable의 인스턴스는 네임스페이스 대신 이 별칭을 사용하여 생성됩니다.

using colAlias = System.Collections;
namespace System
{
    class TestClass
    {
        static void Main()
        {
            // Searching the alias:
            colAlias::Hashtable test = new colAlias::Hashtable();

            // Add items to the table.
            test.Add("A", "1");
            test.Add("B", "2");
            test.Add("C", "3");

            foreach (string name in test.Keys)
            {
                // Seaching the gloabal namespace:
                global::System.Console.WriteLine(name + " " + test[name]);
            }
        }
    }
}
A 1
B 2
C 3

참고 항목

개념

C# 프로그래밍 가이드

참조

네임스페이스(C# 프로그래밍 가이드)

. 연산자(C# 참조)

:: 연산자(C# 참조)

extern(C# 참조)