2012-04-04 40 views
2

我試圖通過利用Windows窗體項目中的using namespace來節省一些編碼時間。我在VS2010中使用C++/CLI創建了一個默認的Windows Forms項目。我注意到,這是進口的默認命名空間:在Windows窗體應用程序中使用C++/CLI命名空間混淆

using namespace System; 
using namespace System::ComponentModel; 
using namespace System::Collections; 
using namespace System::Windows::Forms; 
using namespace System::Data; 
using namespace System::Drawing; 

我想創建一個DialogResult -typed變量,它(方便夠了!)坐在System::Windows::Forms命名空間中。我去到構造默認Form1,並添加一行:

DialogResult dr; 

我得到的編譯器錯誤syntax error : missing ';' before identifier 'dr'

但是,如果我改線至:

Windows::Forms::DialogResult dr; 

System::Windows::Forms::DialogResult dr; 

然後一切按預期工作。

我也嘗試添加

using namespace System::Windows; 

然後

Forms::DialogResult dr 

的作品呢!

我錯過了關於這些命名空間是如何工作的?我想避免必須完全限定我正在編寫的所有代碼,但我無法弄清楚我做錯了什麼,因爲我需要的名稱空間應該已經導入。

回答

4

System::Windows::Forms::Form有一個名爲DialogResult的屬性,所以屬於Form子類的屬性的範圍優先於全局名稱空間中的類型。

我通常解決這跟一個typedef:

typedef System::Windows::Forms::DialogResult DialogResult_t; 

然後,你需要使用的類型,使用DialogResult_t任何時候,任何時候你需要訪問屬性,使用DialogResult

請注意,此問題不是C++/CLI特定的– C++具有相同的作用域規則,因此會產生相同的問題;它只是.NET BCL重複使用類型名稱作爲屬性名稱相當廣泛(C++代碼將避免這種情況),因爲C#沒有此問題。

+0

Grr!我應該想出這一個,但很好的解釋和有用的建議!非常感謝! – aardvarkk 2012-04-04 17:03:55

相關問題