这个问题在这里已经有了答案:
Nested namespaces
(5 个回答)
6年前关闭。
给定以下命名空间结构:
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; } } }
为什么我会出现以下行为?
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;
}
}
}
我曾相信在命名空间中使用句点与嵌套它具有相同的效果(即
namespace A.A1 { }
== namespace A { namespace A1 { } }
),并且 using
指令将允许我在将来的使用中省略该部分。不是这样吗?
最佳答案
来自 using Directive页:
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.
你不能做你想做的。
举一个更简单的例子:
using System;
public class Foo
{
public void Bar()
{
// Compilation error!
// You need new System.Collections.Generic.List<int>();
new Collections.Generic.List<int>();
}
}
关于c# - 使用嵌套命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30164689/