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

流过昼夜 提交于 2019-11-28 14:03:04

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
}

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.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!