Why can one aliased C# Type not be accessed by ano

2019-01-20 13:17发布

问题:

good stuff

// ok to alias a List Type
using AliasStringList = System.Collections.Generic.List<string>;

// and ok to alias a List of Lists like this
using AliasListOfStringList1 = System.Collections.Generic.List<System.Collections.Generic.List<string>>;

bad stuff

// However **error** to alias another alias
using AliasListOfStringList2 = System.Collections.Generic.List<AliasStringList>;

Produces the compile error

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

Note: this is the using directive not the using statement.

回答1:

You just can't use an alias declared in a using inside another using. For a set of usings like you have, you can assume that sibling using declarations don't exist.

From MSDN

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

It provides simplified example of your exact problem, this is expected behavior:

namespace N1.N2 {}
namespace N3
{
   using R1 = N1;         // OK
   using R2 = N1.N2;      // OK
   using R3 = R1.N2;      // Error, R1 unknown
}


回答2:

The documentation says:

The right side of a using alias directive must always be a fully-qualified type regardless of the using directives that come before it.

So basically alias directives ignore other using directives.



回答3:

Although this question doesn't ask for a solution to eliminate the compile error while This duplicate question is asking about, I will list what I have found so far.

  • Solution0: independent namespace (Nick's answer)

  • Solution1: nested namespace (inspired by Nick's answer)

    using StringList = System.Collections.Generic.List<string>;
    namespace Inner {
        using ListOfStringList = System.Collections.Generic.List<StringList>;
        ...
    }
    
  • Solution2: inheritance (Paul's answer)

    using StringList = System.Collections.Generic.List<string>;
    public class ListOfStringList : System.Collections.Generic.List<StringList> {}
    ...
    

But there will be some problems with Solution2 that you may have to wrap all constructors of the System.Collections.Generic.List<StringList>.



标签: c# .net alias