2017-09-01 85 views
4

我試圖使用using指令以功能方式定義類型,使代碼更具可讀性。比方說,我的example.cs文件看起來像這樣:使用嵌套類型定義指令

using A = System.Tuple<int, int>; 
using B = List<A>; 

我得到的錯誤:

CS0246 The type or namespace name 'A' could not be found (are you missing a using directive or an assembly reference?)

我可以定義嵌套類型與using或者是不可能的?

+4

'using B = System.Collections.Generic.List >;'。隨着使用你不能使用另一個使用,總是指定類型名稱。您在定義'A'時已經體驗過這一點,是嗎? '使用系統;'不能修復錯誤。 – Sinatr

+1

@SzymonPajzert,我希望你不介意,但是當我將它放到.cs文件中以替換你的釋義版本時,我添加了從代碼段生成的錯誤。我已經這樣做了,以便未來其他人更容易找到問題 - 如果您遇到不同的錯誤(因爲我錯誤地解釋了您的問題),請將更新回滾或更新你得到的具體錯誤=) – Rob

回答

4

上docs.microsoft.com的C#語言規範具有覆蓋Using directive,特別是使用你試圖使用指令的類型是「Using alias directive」一節:

A using_alias_directive (Using alias directives) introduces an alias for a namespace or type.

文檔亮點一個using_alias_directive作爲允許結構:

using_alias_directive 
    : 'using' identifier '=' namespace_or_type_name ';' 
    ; 

注意,這僅允許應該說這是「namespace_or_type_name」,但不允許使用的另一個「using_alias_directive」。一對,這個可能的原因可以發現一部分的方式,通過對他們(重點煤礦)的文檔:

The order in which using_alias_directives are written has no significance, and resolution of the namespace_or_type_name referenced by a using_alias_directive is not affected by the using_alias_directive itself or by other using_directives in the immediately containing compilation unit or namespace body. In other words, the namespace_or_type_name of a using_alias_directive is resolved as if the immediately containing compilation unit or namespace body had no using_directives

總之,你不能在另一個別名使用別名,我害怕。

+0

所有帶有「組織/排序'使用'指令」特性的重構工具的作者都鬆了一口氣。 –

+0

@JeroenMostert,這是本世紀的輕描淡寫! =) – Rob