C# using alias as type parameter in other using alias

前端 未结 5 1205
既然无缘
既然无缘 2021-01-13 01:33

I\'m trying to define a pair of type aliases at the top of my C# program. This is a short example of what I\'m trying to do:

using System;
using System.Colle         


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 02:00

    Check documentation for this question:

    https://msdn.microsoft.com/en-us/library/aa664765(v=vs.71).aspx

    It says:

    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. In the example

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

    the last using-alias-directive results in a compile-time error because it is not affected by the first using-alias-directive.

    Technically, you cannot do it same namespace, but if you do alias in namespace 1, and do alias for this alias in a nested namespace, it will work:

    namespace N1
    {
        namespace N12 { }
    }
    
    namespace N2
    {
        using R1 = N1;
    
        namespace N2
        {
            using R2 = R1.N12;
        }
    }
    

    I am not really sure it's worth using aliases in your specific example, consider using them as rare as you can, mostly for resolving namespace conflicts.

提交回复
热议问题