The reason I ask this is that c# could easily have copied the java convention, or a variation of it, but opted for the more flexible approach of explicitly declaring namespaces inside files. As a Java programmer often there are things that I wish I could do differently, but namespaces is not one of them.
The flexbility has a certain overhead (extra braces, extra decisions for developers, making it harder to view a projects contributions to the namespace, at least without a specialist IDE). So what practical examples开发者_开发技巧 are there when this flexiblity is advantageous?
edit: To clarify, the point is how classes declare themselves within namespaces and not how to import/reference classes from other namespaces.
It could be useful in generated code. Sometimes code generation may wish to create a single source file for multiple classes - and they may be in different namespaces.
A problem I see with the Java convention is there is no way to specify multiple imports of the same classname in different packages. So suppose you have two classes like...
com.yourcompany.blah.blah.verylong.blah.blah.FantasticClass
com.someothercompany.blah.blah.also.very.lengthy.blah.blah.FantasticClass
...inside of one Java file, you can use import on just one of them. If your code needs to use both classes, then you'll have to write variable declarations for one of them with the full package name. That means you end up with cumbersome code like...
com.someothercompany.blah.blah.also.very.lengthy.blah.blah.FantasticClass = new com.someothercompany.blah.blah.also.very.lengthy.blah.blah.FantasticClass();
...or weird refactoring exercises to avoid it.
Other than that hiccough, which could be fixed pretty easily with a new language feature like "import class alias class2", I prefer the simplicity of the Java approach.
From code design view namespace is same as package. Good style in Java is to put classes into packages based on their roles in your application. It increases readability and maintainability of code. From this point of view namespaces are the same. But namespace doesn't force you to put classes in different folders.
精彩评论