c# - c# 是否有类似 'child' 的命名空间,或者像 Java 中的包作用域?

标签 c# namespaces

我不明白为什么在这种情况下不需要显式引用:

//SomeStaticClass.cs
namespace WhyDontINeedUsingStatement {

    public static class SomeStaticClass {
        public static string Thingy {
            get { return "Behold! A thingy!"; }
        }
    }

    public class SomeNonStaticClass {
        public void DoSomethingUseful() {
            var foo = 9; 
        }
    }
}

// /SomeNamespace/SomeBoringClass.cs
namespace WhyDontINeedUsingStatement.SomeNamespace {
    public class SomeBoringClass {
        public static void DoSomething() {
            var whatever = SomeStaticClass.Thingy;

            var blah = new SomeNonStaticClass();
            blah.DoSomethingUseful();            
        }
    }
}

为什么这不需要 using WhyDontINeedUsingStatement在顶部?这些不是独立的命名空间,即使它们以相同的东西开始吗?

我知道 C# 命名空间与 Java 包并不完全相同(并且不影响访问控制),但不是为什么第二个类能够引用第一个类的内容。

最佳答案

根据 C# 语言规范版本 5.0,第 9.2 节,似乎使用了 .在命名空间声明中是语法糖:

The qualified-identifier of a namespace-declaration may be a single identifier or a sequence of identifiers separated by “.” tokens. The latter form permits a program to define a nested namespace without lexically nesting several namespace declarations. For example,


namespace N1.N2
{
    class A {}
    class B {}
}

is semantically equivalent to


namespace N1
{
    namespace N2
    {
        class A {}
        class B {}
    }
}

所以从 N2 内部你可以看到N1 ,因此您可以使用它。

关于c# - c# 是否有类似 'child' 的命名空间,或者像 Java 中的包作用域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28246904/

相关文章:

namespaces - Fortran 命名空间冲突

c# - 可空启用与 T 的集合

c# - 如何在 VS C# 控制台应用程序中使用引用的 c# dll 代码

c# - 使用x :Name in MVVM动态添加控件

php - 命名空间和特征

wcf - WCF 和多个命名空间的问题 - 跨多个服务引用共享对象类型

c# - 给定单例缓存模式的缺点

c# - 你能从 C# 中的泛型中获取类型特定的行为吗?

C++,静态与命名空间与单例

c# - 命名空间和类名冲突