简体   繁体   中英

Howto access a namespace with the same name as a class instance?

I have a question regarding namespace names and classes:

If I have a class called cVeloConnect in namespace VeloConnect. eg

namespace VeloConnect
{
    public class cVeloConnect
    {
        // Some content
        public void PrintMe();

    }

    public class cSomeClass
    {
        // Some content

    }
}

And now I want to create a new instance of cVeloConnect, calling this instance VeloConnect, I cannot access the VeloConnect namespace anymore... eg

VeloConnect.cVeloConnect VeloConnect = new VeloConnect.cVeloConnect();
VeloConnect.PrintMe();
// The below thing is not possible
VeloConnect.cSomeClass MyClass = new VeloConnect.cSomeClass();

How can I access the other class, if I don't want to rename the namespace or my previous instance ?

Well, one option is to follow naming conventions to avoid this sort of thing - your classes shouldn't start with c , and your local variables would normally start with a lower case letter.

To avoid having to use the namespace at all in the declaration, you can just use a using directive at the top of your code. Or if you really want to specify the namespace, you could use global:: :

global::VeloConnect.cSomeClass MyClass = new global::VeloConnect.cSomeClass();

In general though, I don't like seeing namespaces within my actual code - I prefer having using directives so I can just use the simple names in the body of the code. Either way, I would strongly urge you to start following the .NET naming conventions .

Alias the namespace;

 using vc=VeloConnect;

 // ... then, later ....

 vc.cVeloConnect VeloConnect = new vc.cVeloConnect();
 VeloConnect.PrintMe();
 // The below thing is not possible
 vc.cSomeClass MyClass = new vc.cSomeClass();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM