C#中的global::system***命名空間別名限定符

來源:互聯網
上載者:User

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);
    }
}

由於類 TestApp.System 隱藏了
System 命名空間,因此使用
System.Console 仍然會導致錯誤:

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

但是,可以通過使用 global::System.Console
避免這一錯誤,如下所示:

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

顯然,並不推薦建立自己的名為 System
的命名空間,您不可能遇到出現此情況的任何代碼。但是,在較大的項目中,很有可能在一個表單或其他表單中出現命名空間重複。在這種情況下,全域命名空間限定符可保證您可以指定根命名空間。

global 是 C# 2.0
中新增的關鍵字,理論上說,如果代碼寫得好的話,根本不需要用到它。

假設你現在寫了一個類,名字叫 System。那麼當你再在代碼裡寫 System
的時候,編譯器就不知道你是要指你寫的 System 類還是系統的 System 命名空間,而 System
命名空間已經是根命名空間了,無法再通過完全限名來指定。在以前的 C# 版本中,這就是一個無法解決的問題。現在,可以通過

global::System 來表示 System
根命名空間,

而用你自己的 MyNamespace.System 
來表示自己的類。

當然,這種情況不應該出現,你不應該寫一個名為 System 的類。

轉自:http://www.cnblogs.com/distance/archive/2011/04/20/2022202.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.