Why can one aliased C# Type not be accessed by another?

后端 未结 3 1214
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 22:28

good stuff

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

// and ok to alias a List of Lists like this
us         


        
相关标签:
3条回答
  • 2020-12-11 22:53

    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
    }
    
    0 讨论(0)
  • 2020-12-11 23:07

    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.

    0 讨论(0)
  • 2020-12-11 23:15

    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>.

    0 讨论(0)
提交回复
热议问题