C# 2.0 之 :: 别名限定修饰符(namespace alias qualifier )

参考以下 C# 代码:

namespace MyApp { public class Sample { public void SampleMethod() { System.Console.WriteLine("hello"); } } }

这没有任何问题,但是如果我的程序中有这样的一个 namespace :

namespace MyApp.System { public class Test { public static void t() { } } }

编译这段代码,出错:类型或命名空间名称“Console”在类或命名空间“MyApp.System”中不存在(是否缺少程序集引用?)

我们只能通过更改 namespace 的名称来避免这个问题的出现。

在 C# 2.0 中,这段代码编译仍然会出错,不过我们有了解决的办法。

System.Console.WriteLine("hello")
修改为
global::System.Console.WriteLine("hello")
就可以了。

这里的 :: 就是别名限定修饰符。

另外如果你使用 using M = MyApp.System,你就可以使用 M::Test 来限定为 MyApp.System.Test,这里 :: 其实没有什么意义,因为它和 M.Test 的效果是一样的。

写了三篇,都是一些无关痛痒的细节问题,我一直在逃避范型、迭代器这些关键的内容,我可怜的文字表达能力。

我要把我所能找到的这种无关痛痒的细节问题都写出来,再去动那些难啃的骨头,给我自己一点时间。

posted on 2004-05-24 13:30  刘敏(Rustle Liu)  阅读(1080)  评论(1编辑  收藏  举报