简体   繁体   中英

“using” type alias directive doesn't work in same namespace

Hi I have a simple question

namespace A
{
    using TupleA = Tuple<int, int>;
    namespace B
    {       
        using DicB = Dictionary<TupleA, int>;       
    }
}    

It can be complied.. but this is not.

namespace A
{
    using TupleA = Tuple<int, int>;
    using DicB = Dictionary<TupleA, int>;               
}    

Second case, The compiler can't find the 'TupleA' type! How can I make it works? I'm using .Net Framework 4.5

You cannot make the exact syntax you want work. This is because of the following passage from the C# specification (see "9.4.1 Using alias directives" ):

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 C# compiler has to be able to process all of the using alias directives in a given declaration space in isolation. Because order doesn't matter, one directive cannot reference an alias in the same declaration space. Otherwise, the compiler would have to perform multiple passes through the alias directives, iteratively declaring as many as it could and trying again, until it successfully declared all aliases, or ran out of new things to declare.

As you already have seen in your own test, you can declare the alias in a declaration space containing the declaration space where you want to use it. This imposes an order to the declarations and allows the alias to be used.

the following will work

namespace A
{
   using TupleA = System.Tuple<int, int>;
   using DicB = System.Collections.Generic.Dictionary<System.Tuple<int, int>, int>;   
}  

or if you must

 using TupleA = System.Tuple<int, int>;
 namespace A
 {

    using DicB = System.Collections.Generic.Dictionary<TupleA, int>;   
 }  

Update

MSDN relevant to what you are trying to do 9.3.1 Using alias directives

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM