使用嵌套命名空间

时间:2015-05-11 10:00:27

标签: c# .net namespaces

给定以下命名空间结构:

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指令允许我省略将来使用的那部分。情况不是这样吗?

3 个答案:

答案 0 :(得分:2)

来自using Directive页面:

  

创建using指令以使用命名空间中的类型,而无需指定命名空间。 using指令不允许您访问嵌套在指定名称空间中的任何名称空间。

你无法做你想做的事。

举一个更简单的例子:

using System;

public class Foo
{
    public void Bar()
    {
        // Compilation error!
        // You need new System.Collections.Generic.List<int>();
        new Collections.Generic.List<int>();
    }
}

答案 1 :(得分:0)

如果使用句点创建名称空间,则名称空间名称将包含句点。但是,您可以使用句点访问嵌套命名空间。例如,namespace A.A1将命名为A.A1,但

   namespace A
    {
        namespace A1 { }
    }

您可以通过using A.A1访问。

答案 2 :(得分:0)

由于您的所有3个类都具有相同的名称MyInt,因此您必须明确说明您指的是哪个类。

这就是为什么这两个例子都会导致错误

// Error: MyClass is ambiguous
MyClass.MyInt = 5;
// Error: The type or namespace A1/B1 could not be found.
A1.MyClass.MyInt = 5;

在本例中明确定义它们:

A.A1.MyClass.MyInt = 5;
B.B1.MyClass.MyInt = 5;

在这种情况下完全正常,使用部分是不必要的。

虽然有时可能会有同名的类,但这种情况非常罕见,而且在同一个环境中使用它们的情况更为罕见。

问题是你想要实现的目标?