Namespace and class with the same name?

前端 未结 9 1734
终归单人心
终归单人心 2020-11-29 03:38

I\'m organizing a library project and I have a central manager class named Scenegraph and a whole bunch of other classes that live in the Scenegraph namespace.<

9条回答
  •  忘掉有多难
    2020-11-29 04:12

    I don't recommend you to name a class like its namespace, see this article.

    The Framework Design Guidelines say in section 3.4 “do not use the same name for a namespace and a type in that namespace”. That is:

    namespace MyContainers.List 
    { 
        public class List { … } 
    }
    

    Why is this badness? Oh, let me count the ways.

    You can get yourself into situations where you think you are referring to one thing but in fact are referring to something else. Suppose you end up in this unfortunate situation: you are writing Blah.DLL and importing Foo.DLL and Bar.DLL, which, unfortunately, both have a type called Foo:

    // Foo.DLL: 
    namespace Foo { public class Foo { } }
    
    // Bar.DLL: 
    namespace Bar { public class Foo { } }
    
    // Blah.DLL: 
    namespace Blah  
    {   
    using Foo;   
    using Bar;   
    class C { Foo foo; } 
    }
    

    The compiler gives an error. “Foo” is ambiguous between Foo.Foo and Bar.Foo. Bummer. I guess I’ll fix that by fully qualifying the name:

       class C { Foo.Foo foo; } 
    

    This now gives the ambiguity error “Foo in Foo.Foo is ambiguous between Foo.Foo and Bar.Foo”. We still don’t know what the first Foo refers to, and until we can figure that out, we don’t even bother to try to figure out what the second one refers to.

提交回复
热议问题