Namespaces in C# vs imports in Java and Python

后端 未结 6 1760
一整个雨季
一整个雨季 2021-02-20 03:21

In the Java and Python world, you look at a source file and know where all the imports come from (i.e. you know in which file the imported classes are defined). For example:

6条回答
  •  轮回少年
    2021-02-20 03:56

    For Java and Python this is indeed an issue with conventions - import the class you need, not the entire package using wildcards.

    In C# you can't do a using directive for the specific class you want, since it only works for namespaces (as the following error reveals). It would seem that C# remained true to the C++ concept of namespaces, and merged it with the #include directive for one easy way of referencing external classes.

    using System.Net.Sockets.Socket; // Gives the following error:
    
    // A using namespace directive can only be applied to namespaces; 
    // 'System.Net.Sockets.Socket' is a type not a namespace
    

    And about the double Bar deceleration, it's simple - if the compiler has no way of knowing it will give an error:

    using Foo; // Has class Bar {}
    using Goo; // Has class Bar {}
    
    Bar b = new Bar(); // Gives the following error:
    // 'Bar' is an ambiguous reference between 'Foo.Bar' and 'Goo.Bar'
    

提交回复
热议问题