Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
637 views
in Technique[技术] by (71.8m points)

c# - Nested namespaces

I've got something like this:

namespace n1
{
    namespace n2
    {
        class foo{}
    }
}

In other file I write:

using n1;

Why I can't type now something like:

n2.foo smthing;

And how to make something like this possibile?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a deliberate rule of C#. If you do this:

namespace Frobozz
{
    namespace Magic
    {
        class Lamp {}
    }

    class Foo
    {
        Magic.Lamp myLamp; // Legal; Magic means Frobozz.Magic when inside Frobozz
    }
}

That is legal. But this is not:

namespace Frobozz
{
    namespace Magic
    {
        class Lamp {}
    }
}

namespace Flathead
{
    using Frobozz;
    class Bar
    {
        Magic.Lamp myLamp; // Illegal; merely using Frobozz does not bring Magic into scope
    }
}

The rule of C# that describes this is in section 7.6.2 of the C# 4 spec. This is a very confusing section; the bit you want is the paragraph near the end that says

Otherwise, if the namespaces imported by the using-namespace-directives of the namespace declaration contain exactly one type having name I...

The key point is that it says "exactly one type", not "exactly one type or namespace". We deliberately disallow you "slicing" a namespace name like this when you are outside of that namespace because it is potentially confusing. As others have said, if you want to do that sort of thing, fully qualify it once in a using-alias directive and then use the alias.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...