0

我在看这个页面MSDN: Global namespace alias

他们在那里有以下代码。

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()
    {
        // The following line causes an error. It accesses TestApp.Console, 
        // which is a constant. 
        //Console.WriteLine(number);
    }
}

他们给出了进一步的例子。

我了解如何global在这里使用:

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

但是,我不明白以下内容的作用(尤其是在同一行中如何使用global::TestApp和使用)::

class TestClass : global::TestApp

MSDN 页面对上述代码进行了说明:“以下声明将 TestApp 引用为全局空间的成员。” .

有人可以解释一下吗?

谢谢。

4

3 回答 3

3

这是对存在于全局级别的类 TestApp 的强命名,类似于 System。如果您说class TestClass : global::System.Console您将继承全局系统控制台(如果这是合法的)。因此,在此示例中,您将继承在全局范围内定义的 TestApp。

因此,为了更清楚起见,请考虑以下命名空间模型:

namespace global
{
    // all things are within this namespace, and therefor
    // it is typically deduced by the compiler. only during
    // name collisions does it require being explicity
    // strong named

    public class TestApp
    {
    }

    namespace Program1
    {
        public class TestClass : global::TestApp
        {
            // notice how this relates to the outermost namespace 'global'
            // as if it were a traditional namespace.
            // the reason this seems strange is because we traditionally
            // develop at a more inner level namespace, such as Program1.

        }
    }       
}
于 2013-09-20T19:01:06.987 回答
1

两者global的使用方式相同:

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

    System.Console.WriteLine(number);

作为

    class TestClass : global::TestApp

    class TestClass : TestApp

单个冒号只是常规继承。

于 2013-09-20T19:10:36.643 回答
1

也许这个例子会更好地说明它:

代码:

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            var myClass1 = new MyClass();
            var myClass2 = new global::MyClass();
        }

        public class MyClass { }
    }
}

public class MyClass { }

解释:

myClass1Test命名空间中类的一个实例

myClass2是命名空间中类的一个实例global,也就是没有命名空间。

global::可用于访问被本地定义的对象隐藏的项目。在这种情况下,Test.MyClass隐藏对global::MyClass.

于 2013-09-20T19:14:56.083 回答