问题
Given the following namespace structures:
namespace A { public static class MyClass { public static int MyInt; } }
namespace A.A1 { public static class MyClass { public static int MyInt; } }
namespace B { namespace B1 { public static class MyClass { public static int MyInt; } } }
Why do I get the following behaviour?
namespace C {
using A;
using B;
public class SomeClass {
public void foo() {
// Valid, but renders 'using' directives obsolete
A.A1.MyClass.MyInt = 5;
B.B1.MyClass.MyInt = 5;
// Error: The type or namespace A1/B1 could not be found.
A1.MyClass.MyInt = 5;
B1.MyClass.MyInt = 5;
}
}
}
namespace D {
using A.A1;
using B.B1;
public class SomeClass {
public void bar() {
// Valid, but renders 'using' directives obsolete
A.A1.MyClass.MyInt = 5;
B.B1.MyClass.MyInt = 5;
// Error: MyClass is ambiguous (of course)
MyClass.MyInt = 5;
// Error: The type or namespace A1/B1 could not be found.
A1.MyClass.MyInt = 5;
}
}
}
I had believed that using periods in a namespace would have the same effect as nesting it (ie namespace A.A1 { }
== namespace A { namespace A1 { } }
), and that the using
directive would allow me to omit that portion in future uses. Is this not the case?
回答1:
From the using Directive page:
Create a using directive to use the types in a namespace without having to specify the namespace. A using directive does not give you access to any namespaces that are nested in the namespace you specify.
You can't do what you wanted.
To give a simpler example:
using System;
public class Foo
{
public void Bar()
{
// Compilation error!
// You need new System.Collections.Generic.List<int>();
new Collections.Generic.List<int>();
}
}
回答2:
If you create a namespace with a period, the namespace name will contain a period. However you can access nested namespaces using a period. For example namespace A.A1
will be named A.A1, but
namespace A
{
namespace A1 { }
}
This you can access via using A.A1
.
回答3:
Since all 3 of your classes have same name MyInt
you have to explicitly say to which class in which namespace are you referring to.
Thats why both these examples result in error
// Error: MyClass is ambiguous
MyClass.MyInt = 5;
// Error: The type or namespace A1/B1 could not be found.
A1.MyClass.MyInt = 5;
having them explicitly defined as in this example :
A.A1.MyClass.MyInt = 5;
B.B1.MyClass.MyInt = 5;
Is perfectly normal in this situation and the using part is unnecesery.
While it is sometimes possible to have classes with same name, it is very rare, and its even more rare that you will use both of them in same context.
Question is what are you trying to achieve?
来源:https://stackoverflow.com/questions/30164689/using-nested-namespaces