我想知道为什么我在命名空间范围之外定义类时可以访问它?
我对命名空间不是很熟悉,我只是在学习,但我认为命名空间应该将我所有的类包装到一个“盒子”中,并且它们可以在那个“盒子”(范围)内相互访问。
代码示例:
class Point
{
public int X;
}
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
Point p = new Point();
p.X = 50;
Console.WriteLine(p.X);
Console.ReadLine();
}
}
}
感谢您的回答。
最佳答案
命名空间与访问无关。区分命名空间和程序集很重要 - 它们通常密切相关,因为命名空间 Foo.Bar
中的类型很可能在程序集中 Foo.Bar.dll
,但这是一个约定 - 它不是编译器或语言关心的东西。
命名空间主要是“名称必须唯一的空间”。换句话说,虽然在不同的命名空间中有两种名为 Point
的类型是可以的,但是您不能在相同中有两种名为 Point
的类型命名空间。事实上,存在命名空间 (IMO) 的主要原因是我们不必在世界上的每一段 .NET 代码中都必须使用完全唯一的名称。
您可以使用您的 Point
类,只要它是在同一个程序集中声明的,它是隐式 internal
的。如果它在全局命名空间中(即根本没有在命名空间中声明),那么您不需要任何 using
指令来引用它 - using
指令的目的是允许您仅通过短名称来引用不同命名空间的成员。
如果你有:
namespace Foo.Bar
{
public class Baz {}
}
然后你可以访问它:
namespace Other
{
class Test
{
Foo.Bar.Baz baz = new Foo.Bar.Baz();
}
}
或
// Allow anything in namespace Foo.Bar to be accessed by its
// short name
using Foo.Bar;
namespace Other
{
class Test
{
Baz baz = new Baz();
}
}
如果类型是在“全局”命名空间中定义的,那么您就不需要 using
指令。来自 C# 5 语言规范第 3.8 节(命名空间和类型名称),其中描述了类型名称查找过程:
If the previous steps were unsuccessful then, for each namespace N, starting with the namespace in which the namespace-or-type-name occurs, continuing with each enclosing namespace (if any), and ending with the global namespace, the following steps are evaluated until an entity is located
所以在你的情况下,从你的 Main
方法中寻找 Point
,首先 ConsoleApplication12
将检查 Point
类型,然后是全局命名空间。
关于c# - 为什么我可以访问在命名空间之外定义的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45232068/