Namespace, assembly, and inheritance hierarchy when including

China☆狼群 提交于 2019-12-25 02:29:27

问题


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. However, if I also want to use an IEnumerator, I also have to include the System.Collections namespace. Shouldn't System.Collections already be referenced by any member of System.Collections.Generic, as it is a child? Both namespaces also share the same assembly, mscorlib.dll.

Why is the parent namespace not included when the child is?


回答1:


Shouldn't System.Collections already be referenced by any member of System.Collections.Generic, as it is a child?

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.

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.

The only exception to this is that if you're writing code within a namespace declaration of X.Y.Z, that implicitly imports namespaces X.Y and X (as well as X.Y.Z, of course). (In that example, X.Y is the enclosing namespace if X.Y.Z, but it's not an inheritance relationship.)



来源:https://stackoverflow.com/questions/23613887/namespace-assembly-and-inheritance-hierarchy-when-including

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!