简体   繁体   中英

Why does C# requires either no namespaces or full namespaces (fully qualified name)?

I always thought about this but never understood why.

Simple example:

public IEnumerator<Effect> GetEnumerator ( )
{
    return this.Effects.GetEnumerator ( );
}

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator ( )
{
    return this.GetEnumerator ( );
}

Why do you have to specify:

System.Collections.IEnumerator

but not just:

Collections.IEnumerator

I am not saying this is better but to me it seems like it's a step by step approach to solve collisions.

Because sometimes there are quite deeply nested types, so having to type the full name because of a collision feels bad, instead of just prefixing the type with the immediate namespace that contains it so the compiler can try to find it in the currently imported/used namespaces.

Also when I first started C#, I always find myself doing this, thinking this is how it would work. It would be cool to see how other people would have behaved coming fresh to C#, having never used namespace concepts before.

I think Foo Bah was trying to say this:

using Collections = System.Collections;

Note that the correct place for this one is inside the namespace and outside the class, like this:

namespace MyNamespace
{
    using SysCollections = System.Collections;

    public class MyClass
    {
        SysCollections.ArrayList mySampleField;
    }
}

I meant to use SysCollections to show there is no restrictions on that alias naming.

Also, note that using System is exactly the 'using System.*' that you want.

So, this works, and it's what most people would do:

using System;

namespace MyNamespace
{
    public class MyClass
    {
        Collections.ArrayList mySampleField;
    }
}

write

using System.Collections;

Then you can write the short-form Collections.IEnumerator

Because there is no such thing as using System.*;

This would work:

namespace System
{

   /*System.*/Collections.IEnumerator GetEnumerator ( )
   {
       return this.GetEnumerator ( );
   }


}

But you should not add anything to System lightly.

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