c# - 使用嵌套命名空间

标签 c# .net namespaces

这个问题在这里已经有了答案:





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/

相关文章:

php - 如何修复新文件夹项目中未确定的命名空间?

c# - 使用 HTTPStatusCodeResult 和 jQuery 的自定义错误消息

c# - 如何使用 ValueConversions 检索 Entity Framework Core 的数据库模型

c# - 如何通过 ValueMember 选择 ListBox 项

c# - 将现有的 SqlMembershipProvider 数据库与 ASP.NET MVC 应用程序一起使用

Swift - 当框架/模块具有相同名称的类时不能使用命名空间

c# - 如何将其他文件发布到 bin 文件夹中

c# - 为正则表达式禁用全局

.net - ASP.NET MVC 和 ADO.NET Entity Framework 中的最佳实践实体验证

testing - 与内容重复的 kubernetes 命名空间