使用指令导入子命名空间
如果我导入这样的命名空间:
using System;
为什么我不能像这样访问子命名空间 IO:
IO.FileInfo fi;
Insted 我必须编写整个路径:
System.IO.FileInfo fi;
或者导入整个 IO 命名空间并使用没有命名空间的类
using System.IO;
FileInfo fi;
我在这里遗漏了什么吗?
If I import a namespace like this:
using System;
Why can't I access subnamespace IO like this:
IO.FileInfo fi;
Insted I must write either a whole path:
System.IO.FileInfo fi;
Or import whole IO namespace and use class without namespace
using System.IO;
FileInfo fi;
Am I missing something here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
虽然用“命名空间”和“子命名空间”来思考通常很方便,但实际上,只有类型名称。
在本例中,只有一个类型:
System.IO.FileInfo
using 指令允许编译器将
System.
添加到任何类型以查看是否找到匹配的类型姓名。但是,这不会找到IO.FileInfo
,因为它将查找包含FileInfo
嵌套类型的IO
类型。该语言的设计方式可能看起来更麻烦,但它消除了嵌套类型名称与命名空间名称的混淆,因为它只查找 using 指令中定义的命名空间内的类型。这减少了类型命名冲突的机会。
While it's often convenient to think in terms of "namespaces" and "sub-namespaces", in reality, there are only type names.
In this case, there is a single type:
System.IO.FileInfo
The using directive allows the compiler to add
System.
to any type to see if it finds a matching type name. However, this won't findIO.FileInfo
, as it will be looking for aIO
type, containing aFileInfo
nested type.The way the language is designed may seem more cumbersome, but it eliminates the confusion of nested type names vs. namespace names, since it only looks for types within the namespaces defined in the using directives. This reduces the chance of type naming collisions.
C# 并没有真正的子命名空间的概念。命名空间名称中的句点仅用于逻辑组织目的。
对于 C# 而言,
System
和System.IO
是两个不同的命名空间。如果您只需要
FileInfo
类,您可以这样做:C# does not really have the concept of subnamespaces. The periods in the namespace name are just there for logical organization purposes.
System
andSystem.IO
are two different namespaces as far as C# is concerned.If you just need the
FileInfo
class you could do this:仅当上下文类型位于同一命名空间层次结构中时,您尝试执行的操作才有效,例如:
您还可以进行相对导入,如下所示:
What you are trying to do only works if the context type is in the same namespace hierarchy, e.g.:
You can also have relative imports, like this: