初探c#(十二)名字空间(Namespaces)

发表于:2007-06-21来源:作者:点击数: 标签:
1.12 名字空间(Namespaces) 我们在前面已对namespace花了不少笔墨(俺都忘了该如何接上了!O.K.请大家看完再倒)。我们曾经说“i not like the hello world”。但是在程序中要经常说就会很累,如果要在别的代码中用就更繁了,这时可以用 namespace搭救。我

   1.12 名字空间(Namespaces)

我们在前面已对namespace花了不少笔墨(俺都忘了该如何接上了!O.K.请大家看完再倒)。我们曾经说“i not
like the hello world”。但是在程序中要经常说就会很累,如果要在别的代码中用就更繁了,这时可以用

namespace搭救。我把第一个例子切开,代码如下:*/

namespace MyOpinion
{
public class Message
{
public string GetMessage() {
return "i dont like Hello world";
}
}
}

/*
如果我想用namespace建立一个自己的库,就要对我的自定义函数和类进行分类,并填入相应的namespace中。
如:*/

namespace Mylib.Csharp.MyOpinion
{
public class Message
{
public string GetMessage() {
return "i dont like Hello world";
}
}
}

/*
namespace是分等级的,“Mylib.Csharp.MyOpinion”其实是缩写,每个“.”后面的namespace都被它前面的包
含。如果拆开:*/

namespace Mylib
{
namespace Csharp
{
namespace MyOpinion
{....}
}
}

/*
然后,我们就可以用自己的库了:*/

using Mylib.Csharp.MyOpinion;
class test
{
static void Main() {
Message m = new Message();
System.Console.WriteLine(m.GetMessage());
}
}

/*
不过无论我们命名如何小心都会出现重名,即命名冲突。这时可以用别名来解决,比如上面的代码可以这样:*/

using MessageSource = Mylib.Csharp.MyOpinion;
class test
{
static void Main() {
MessageSource m = new MessageSource();
System.Console.WriteLine(m.GetMessage());
}
}

原文转自:http://www.ltesting.net