日期:2008-09-18  浏览次数:20432 次

本节课将介绍C#的名称空间。其目的是: <br>
1.了解什么是名称空间。 <br>
<br>
2.了解如何实现&quot;using&quot;指示符。 <br>
<br>
3.了解&quot;alias&quot; 指示符的用法。 <br>
<br>
4.了解名称空间的成员的内容。 <br>
<br>
在第一课中,你已经在简单的hello程序中看到了&quot;using System;&quot;指示符的使用。该指示符可以让你使用System名称空间中的成员。在第一课中,未及对此作出详细介绍,现在我们来解释一下名称空间的具体用法。一旦学完了本节课,你将了解&quot;using&quot;指示符及其相关内容。 <br>
<br>
作为C#的元素,名称空间可以用来帮助组织程序的结构,可以避免两套代码集中命名的冲突。在程序代码中,使用名称空间是个良好的编程习惯,因为这有助于重用你的程序代码。 <br>
<br>
1.清单6-1. The C# Station Namespace: NamespaceCSS.cs <br>
<br>
// Namespace Declaration<br>
using System;<br>
// The C# Station Namespace<br>
namespace csharp_station {<br>
// Program start class<br>
class NamespaceCSS {<br>
<br>
// Main begins program execution.<br>
public static void Main() {<br>
// Write to console<br>
Console.WriteLine(&quot;This is the new C# Station Namespace.&quot;); <br>
}<br>
}<br>
} <br>
<br>
说明 <br>
<br>
清单6-1演示了如何创建一个名称空间。把单词&quot;namespace&quot;放在&quot;csharp_station&quot;之前,就创建了一个名称空间。&quot;csharp_station&quot;名称空间内的大括号中包含了成员。 <br>
<br>
2.清单6-2 Nested Namespace 1: NestedNamespace1.cs <br>
<br>
// Namespace Declaration<br>
using System;<br>
// The C# Station Tutorial Namespace<br>
namespace csharp_station {<br>
namespace tutorial {<br>
// Program start class<br>
class NamespaceCSS {<br>
// Main begins program execution.<br>
public static void Main() {<br>
// Write to console<br>
Console.WriteLine(&quot;This is the new C# <br>
Station Tutorial Namespace.&quot;); <br>
}<br>
}<br>
}<br>
} <br>
<br>
说明 <br>
<br>
名称空间可以建立一个代码的组织结构。一个良好的编程习惯是:用层次模式来组织你的名称空间。你可以把通用一些的名称放在最顶层,里层则放置一些专用一些的名称。这个层次系统可以用嵌套的名称空间表示。清单6-2演示了如何建立一个嵌套的名称空间。在不同的子名称空间内放置代码,从而组织好你的代码的结构。 <br>
<br>
3.清单6-3. Nested Namespace 2: NestedNamespace2.cs <br>
<br>
// Namespace Declaration<br>
using System;<br>
// The C# Station Tutorial Namespace<br>
namespace csharp_station.tutorial {<br>
// Program start class<br>
class NamespaceCSS {<br>
// Main begins program execution.<br>
public static void Main() {<br>
// Write to console<br>
Console.WriteLine(&quot;This is the new C# Station Tutorial Namespace.&quot;); <br>
}<br>
}<br>
} <br>
<br>
说明 <br>
<br>
清单6-3演示了另外一种编写嵌套的名称空间的方法。在&quot;csharp_station&quot;和&quot;tutorial&quot;之间置入点运算符,表明这是嵌套的名称空间。结果同清单6-2。 相比而言,清单6-3 更易书写。 <br>
<br>
4.清单6-4. Calling Namespace Members: NamespaceCall.cs <br>
<br>
// Namespace Declaration<br>
using System;<br>
namespace csharp_station {<br>
// nested namespace<br>
namespace tutorial {<br>
class myExample1 {<br>
public static void myPrint1() {<br>
Console.WriteLine(&quot;First Example of calling another namespace member.&quot;);<br>
}<br>
}<br>
}<br>
// Program start class<br>
class NamespaceCalling {<br>
// Main begins program execution.<br>
public static void Main() {<br>
// Write to console<br>
tutorial.myExample1.myPrint1(); <br>
csharp_station.tutorial.myExample2.myPrint2(); <br>
}<br>
}<br>
}<br>
<br>
// same namespace as nested namespace above<br>