2017-09-01 82 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