简体   繁体   English

包括时的命名空间,程序集和继承层次结构

[英]Namespace, assembly, and inheritance hierarchy when including

Often when including namespaces or assemblies into my code, I often run into strange cases where a namespace is inherited from another, yet classes from the parent namespace are not available. 通常,当在我的代码中包含名称空间或程序集时,我经常会遇到奇怪的情况,即名称空间是从另一个名称空间继承而来的,而父名称空间的类却不可用。 For example, when using List<> or Dictionary<> , I use the System.Collections.Generic namespace. 例如,当使用List<>Dictionary<> ,我使用System.Collections.Generic命名空间。 However, if I also want to use an IEnumerator , I also have to include the System.Collections namespace. 但是,如果我还想使用IEnumerator ,则还必须包括System.Collections命名空间。 Shouldn't System.Collections already be referenced by any member of System.Collections.Generic , as it is a child? System.Collections的任何成员都不应该已经引用了System.Collections.Generic ,因为它是子级的? Both namespaces also share the same assembly, mscorlib.dll. 两个名称空间还共享同一程序集mscorlib.dll。

Why is the parent namespace not included when the child is? 为什么当子级不包含父级名称空间?

Shouldn't System.Collections already be referenced by any member of System.Collections.Generic, as it is a child? System.Collections.Generic的任何成员都应该已经引用了System.Collections,因为它是孩子?

No. There's no inheritance between namespaces. 不。名称空间之间没有继承。 A using directive only imports types from that namespace - it doesn't import types from namespaces starting with the given namespace, or namespaces included within the given namespace's name. using指令仅从该名称空间导入类型-不会以给定名称空间或给定名称空间名称中包含的名称空间开头的名称空间导入类型。

For example, after: 例如,之后:

using System.Collections;

... that doesn't let you use List<T> as a simple name for System.Collections.Generic.List<T> , nor does it let you use Guid as a simple name for System.Guid . ...不允许您将List<T>用作System.Collections.Generic.List<T>的简单名称,也不允许您将Guid用作System.Guid的简单名称。

The only exception to this is that if you're writing code within a namespace declaration of XYZ , that implicitly imports namespaces XY and X (as well as XYZ , of course). 唯一的例外是,如果您在XYZ的名称空间声明中编写代码,则隐式导入名称空间XYX (当然还有XYZ )。 (In that example, XY is the enclosing namespace if XYZ , but it's not an inheritance relationship.) (在该示例中,如果XYZ ,则XY封闭的名称空间 ,但它不是继承关系。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM