Namespace and class with the same name?

前端 未结 9 1728
终归单人心
终归单人心 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:07

    Even though I agree with other answers in that you should not name your class the same as your namespace there are times in which you cannot comply with such requirements.

    In my case for example I was not the person making such a decision therefore I needed to find a way to make it work.

    So for those who cannot change namespace name nor class name here is a way in which you can make your code work.

    // Foo.DLL: 
    namespace Foo { public class Foo { } }
    
    // Bar.DLL: 
    namespace Bar { public class Foo { } }
    
    // Blah.DLL: 
    namespace Blah
    {
        using FooNSAlias = Foo;//alias
        using BarNSAlias = Bar;//alias
        class C { FooNSAlias.Foo foo; }//use alias to fully qualify class name
    }
    

    Basically I created namespace "aliases" and that allowed me to fully qualify the class and the Visual Studio "confusion" went away.

    NOTE: You should avoid this naming conflict if it in your control to do so. You should only use the mentioned technique when you are not in control of the classes and namespaces in question.

提交回复
热议问题