Namespaces in C# vs imports in Java and Python

后端 未结 6 1487
一整个雨季
一整个雨季 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:57

    1) Well, you can do the same thing in Java too:

    import java.util.*;
    import java.io.*;
    
    ...
    
    InputStream x = ...;
    

    Does InputStream come from java.util or java.io? Of course, you can choose not to use that feature.

    Now, in theory I realise this means when you're looking with a text editor, you can't tell where the types come from in C#... but in practice, I don't find that to be a problem. How often are you actually looking at code and can't use Visual Studio?

    2) You can use the same convention in .NET too, of course - and I do, although I don't have empty directories going up the chain... so if I'm creating a project with a default namespace of X.Y, then X.Y.Foo would be in Foo.cs, and X.Y.Z.Bar would be in Z\Bar.cs

    That's also what Visual Studio will do by default - if you create a subfolder, it will create new classes using a namespace based on the project default and the folder structure.

    Of course, you can also declare types in any old file - but mostly people will follow the normal convention of declaring a type with a corresponding filename. Before generics made delegate declarations rarer, I used to have a Delegates.cs file containing all the delegate declarations for a particular namespace (rather than having a bunch of single-declaration files) but these days that's less of an issue.

提交回复
热议问题