简体   繁体   中英

C#: why is fully-qualified name needed despite using?

I'm making a cross-platform C# drawing library for my own use, modeled after System.Drawing and using as many standard System.Drawing types (such as PointF, RectangleF, Color, and Pen) as possible.

Unfortunately, the Pen class is not provided on iOS. So, when compiling for iOS, I've added this, inside System.Drawing, and designed to be as compatible as possible with the standard System.Drawing.Pen class. So far so good.

Today I added support for line cap and join styles. In the standard framework (but not on iOS), these are defined in the System.Drawing.Drawing2D namespace. So, I added them, again in code that's only compiled on iOS:

namespace System {
    namespace Drawing {
        namespace Drawing2D {
            public enum LineCap {
                Flat,
                Round,
                Square   // (etc.)
            }
        }
    public class Pen {
        public Color Color;
        public float Width;
        public Drawing2D.LineCap StartCap;
        public Drawing2D.LineCap EndCap;
        // (etc.)
        }
    }
}

Now we get to the weird bit. In my main program, where I'm trying to use all this, I have "using System.Drawing;" at the top of the file. I find that, even on iOS, I can now use Pen directly:

Pen p = new Pen(Color.Yellow, 6);

However, if I try to using Drawing2D.LineCap directly, I get a CS0103 error, "The name 'Drawing2D' does not exist in the current context."

p.StartCap = Drawing2D.LineCap.Round;   // <-- ERROR

To make it work, I have to fully qualify the name, like so:

p.StartCap = System.Drawing.Drawing2D.LineCap.Round;   // <-- OK (but sad)

So, I'd like to understand why this is. I know that a fully-qualified name can be required when there are two versions of something, and so the compiler can't work out which you mean. But I can't see the collision in this case. As far as I can tell, MonoTouch does not have a System.Drawing2D namespace at all; I've given it one, so what's the problem?

Nested namespaces are not included. Documentation :

"A using directive does not give you access to any namespaces that are nested in the namespace you specify."

So you should say: using System.Drawing.Drawing2D if you want to use that class.

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