Why can't i use partly qualified namespaces during object initialization?

前端 未结 4 1777
不知归路
不知归路 2020-12-28 20:59

I suspect this is a question which has been asked many times before but i haven\'t found one.

I normally use fully qualified namespaces if i don\'t use that type of

相关标签:
4条回答
  • 2020-12-28 21:08

    This is documented in the standard in 3.8 Namespace and Type Names, but it's a bit convoluted to follow.

    The gist of it that a partial namespace reference is only looked for in the namespace where it occurs, and each layer outwards. using-directives are not checked.

    In your example, ns_1_1.Foo would be found if Foo is found anywhere in:

    Program.Program.ns_1_1.Foo
    Program.ns_1_1.Foo
    ns_1_1.Foo
    
    0 讨论(0)
  • 2020-12-28 21:13

    Partial namespaces will work only if your current class is part of that partial namespace. Using statements are not considered for accessing types through partial namespace.

    For instance this will work because your current namespace is ns_1

    namespace ns_1
    {
        public class Program
        {
            public Program()
            {
                var no_foo = new ns_1_1.Foo();
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-28 21:17

    This obvious way unfortunately not working but you can make all this by an alias namespace:

    using ns_1_1 = ns_1.ns_1_1;
    
    public class Program
    {
        public Program()
        {
            var no_foo = new ns_1_1.Foo();
        }
    }
    
    0 讨论(0)
  • 2020-12-28 21:24

    The documentation says:

    Create a using directive to use the types in a namespace without having to specify the namespace. A using directive does not give you access to any namespaces that are nested in the namespace you specify.

    So the using only includes the types (not the namespaces) that are defined in the specified namespace. In order to access types of nested namespace you need to specify it explicitly with a using directive as you did in your first example.

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