C#名字解析顺序

对这样一段代码

namespace Meyer.System
{
  class MainClass
  {
    static void Main()
    {
      System.Console.WriteLine("Hello");
    }
  }
}

C#编译器认为它“Noname2.cs(7,7): error CS0234: 类型或命名空间名称“Console”在类或命名空间“Meyer.System”中不存在(是否缺少程序集引用?)”

msdn对这个问题的解释:
http://support.microsoft.com/default.aspx?scid=kb;en-us;316734

When you choose names for the custom namespaces in your project, make sure that you do not duplicate namespaces that already exist in the common language runtime or other referenced assemblies. If you duplicate namespace names, code within your namespace resolves to your custom namespace, not the namespace in the common language runtime.

他说与名字解析有关是对的,但这里并没有说清楚,怎么解析到custom namespace
这段代码相关的名字空间结构是这样的

全局命名空间
{
  System
  {
  }
  Meyer
  {
    System
    {
    }
  }
}

这段代码对System.Console.WriteLine的查找过程是这样的。
1. 在Meyer.System查找System没有找到。
2. 在Meyer中查找System,找到Meyer.System命名空间。确定System解析为Meyer.System,直接停止进一步的查找。
3. 在Meyer.System中查找Console,没有找到报错。

C#的名字解析是从当前的命名空间开始,一级一级向上查找,而不是由根(全局命名空间)一级一级向下查找。用dos中的路径来类比的话,使用的是相对路径而不是绝对路径。这样设计有不少好处,具体读者可以试着去体会。

注:看C#语言方面的书,介绍namespace的时候,几乎都没有讲解名字解析。我本想写点这方面的内容,讲叙 C#中的编译单元、using指令、using别名等一些概念。老是不知道该如何组织才能写好。这个问题在我的程序中遇到过,写出来当作一个开头吧。看看我能不能写好这方面的内容。

posted on 2004-04-26 21:00  Meyer  阅读(2651)  评论(14编辑  收藏  举报

导航