【问题标题】:Using nested namespaces [duplicate]使用嵌套命名空间 [重复]
【发布时间】:2015-07-21 18:45:22
【问题描述】:

给定以下命名空间结构:

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 指令将允许我在以后的使用中省略该部分。不是这样吗?

【问题讨论】:

  • 您对行为的哪个确切部分感到惊讶? A1.MyClass.MyInt 不起作用,我并不感到惊讶——命名空间不能那样工作。感觉就像您同时在问几个方面的问题(A1.MyClass.MyInt 是否应该工作,以及 A 和 B 之间的任何区别)。
  • 不,它不是......如果你先using System;然后new Collections.Generic.List<int>();,你可以清楚地看到它
  • 如果您已经在 A 命名空间中,A1.MyClass.MyInt 会起作用。
  • @Liam 是的,我知道为什么会这样:P

标签: c# .net namespaces


【解决方案1】:

由于您的所有 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;

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

虽然有时可能会有同名的类,但这种情况非常少见,在相同的上下文中同时使用它们的情况更是如此。

问题是你想达到什么目的?

【讨论】:

    【解决方案2】:

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

       namespace A
        {
            namespace A1 { }
        }
    

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

    【讨论】:

      【解决方案3】:

      来自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>();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-02-17
        • 1970-01-01
        • 2020-05-20
        • 2011-01-02
        • 2011-01-06
        • 1970-01-01
        • 2019-08-03
        • 2015-07-13
        • 1970-01-01
        相关资源
        最近更新 更多