什么是全球::? [英] What is global::?

查看:139
本文介绍了什么是全球::?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#我看全球:: 用于经常在自动生成的代码。这是不是我使用过自己,所以我不知道目的是什么。有人能解释一下吗?

In C# I see global:: used quite often in auto-generated code. It is not something I have ever used myself so I don't know what the purpose is. Can someone explain this?

推荐答案

全局指的是全局命名空间,它可以用来解决问题,让你可以重新定义类型。例如: -

global refers to the global namespace, it can be used to solve problems whereby you may redefine types. For example: -

class foo
{
    class System
    {

    }

}

如果您要使用系统的地方

If you were to use System where it would be locally scoped in the foo class, you could use: -

global::System.Console.WriteLine("foobar");



访问全局命名空间

to access the global namespace

示例

using System;

class Foo
{
    public void baz()
    {
        Console.WriteLine("Foo 1");
    }
}

namespace Demo
{
    class Foo
    {
        public void baz()
        {
            Console.WriteLine("Foo 2");
        }
    }

    class Program
    {
        protected static global::Foo bar = new global::Foo();

        static void Main(string[] args)
        {
            bar.baz(); // would write Foo 1 to console as it refers to global scope
            Foo qux = new Foo();
            qux.baz(); // would write Foo 2 to the console as it refers to the Demo namespace
        }
    }
}

这篇关于什么是全球::?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆