c# - 嵌套命名空间

标签 c#

我有这样的东西:

namespace n1
{
    namespace n2
    {
        class foo{}
    }
}

在我写的其他文件中:

using n1;

为什么我现在不能输入类似的内容:

n2.foo smthing;

如何让这样的事情成为可能?

最佳答案

这是 C# 的故意规则。如果你这样做:

namespace Frobozz
{
    namespace Magic
    {
        class Lamp {}
    }

    class Foo
    {
        Magic.Lamp myLamp; // Legal; Magic means Frobozz.Magic when inside Frobozz
    }
}

这是合法的。但这不是:

namespace Frobozz
{
    namespace Magic
    {
        class Lamp {}
    }
}

namespace Flathead
{
    using Frobozz;
    class Bar
    {
        Magic.Lamp myLamp; // Illegal; merely using Frobozz does not bring Magic into scope
    }
}

描述这一点的 C# 规则在 C# 4 规范的第 7.6.2 节中。这是一个非常困惑的部分;你想要的是接近尾声的段落

Otherwise, if the namespaces imported by the using-namespace-directives of the namespace declaration contain exactly one type having name I...

关键是它说的是“exactly one type”,而不是“exactly one type or namespace”。当您在该命名空间之外时,我们有意禁止您“切片”这样的命名空间名称,因为这可能会造成混淆。正如其他人所说,如果您想做那种事情,请在 using-alias 指令中完全限定一次,然后使用别名。

关于c# - 嵌套命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6297279/

相关文章:

C# 在运行时构建菜单、commandHandlers 和 hashtable

c# - 将对象序列化为已包含一个 JSON 属性的 JSON

c# - 在互操作方法中为 `null` 参数传递 `ref struct` 引用

c# - 返回 View 后未调用 ASP.NET 索引方法

c# - C# 中的 C 样式 union

c# - DotNetZip 真的使用 WinZipAes256 吗?

c# - 使用任务时如何在 STA 线程上运行

c# - "Namespace ' x ' is not defined"尽管先调用 GetNamespacesInScope

c# - 在 XML 反序列化中使用继承

c# - JSON 解析问题 - 'S' 是 JSON 中无效的可转义字符