简体   繁体   中英

Namespace access issue with sub namespaces

I have two classes in the different sub namespaces:

namespace Acme.ByteTools
{
        class ByteTools
        {
        ...
        }
}

namespace Acme.IO
{
        class Reader
        {
        ...
        }
}

While I trying to access Acme.ByteTools from the any third namespace, I use:

using Acme.ByteTools;
...
ByteTools.BytesToUint(...);

but when I try to access Acme.ByteTools from Acme.IO, compiler require different notation:

using Acme.ByteTools;
...
ByteTools.ByteTools.BytesToUint(...);

Why?

As others including the legendary Eric Lippert have stated...please don't create collisions. I've seen code riddled with using alias directives because of collisions and I simply cannot express how frustrating it is to see a namespace change its name from class to class.

The confusion speaks for itself. Just look at something like this:

namespace ConsoleApplication1
{    
    class Program
    {
        static void Main(string[] args)
        {
            A a = new A();//A's a namespace
            A.A b = new A.A();//A is a namespace this works!
            global::A.A nuts = new A();//This fails...ugh
            Console.ReadLine();
        }
    }
}

namespace A
{    
    class A
    {
        public void DoWork()
        {
            A a = new A();//A's a class
            A.A b = new A.A();//A is a type (class) A.A makes no sense to the compiler
            global::A.A nuts = new A();//Oh but this works fine
        }

    }
}

So the fix is make sure the namespaces and classes are different. A using alias directive using B = A; might ease the pain however that directive can change from file to file and anything to its right must be fully qualified.

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