开发者

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.IEnumera开发者_StackOverflow社区tor

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜