第三节(命名空间)
命名空间
.net Framework 类库由命名空间组成。每个命名空间都包含可在程序中使用的类型:类,结构,枚举,委托和接口。
/*
* Created by SharpDevelop.
* User: BYW
* Date: 2009-2-20
* Time: 23:49
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System ;
namespace CG
{
class Test
{
static void Main()
{
Console.WriteLine ("My name is CG");
A.PrintName a = new A .PrintName ();
a.intro ();
B.PrintName b = new B .PrintName ();
b.intro ();
}
}
}
namespace A
{
public class PrintName
{
public void intro()
{
Console.WriteLine ("My name is A");
}
}
}
namespace B
{
public class PrintName
{
public void intro()
{
Console.WriteLine ("My name is B");
}
}
}
输出结果:
My name is CG
My name is A
My name is B
使用命名空间的好处
代码可分在多个文件中。
命名空间具有扩展性。
可以堆砌出层次式的类组织结构。
/*
* Created by SharpDevelop.
* User: BYW
* Date: 2009-2-20
* Time: 23:49
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System ;
namespace CG
{
class Test
{
static void Main()
{
Console.WriteLine ("My name is CG");
A.A1 .PrintName a = new A .A1 .PrintName ();
a.intro ();
A.A2 .PrintName b = new A.A2 .PrintName ();
b.intro ();
}
}
}
namespace A
{
namespace A1
{
public class PrintName
{
public void intro()
{
Console.WriteLine ("My name is A");
}
}
}
namespace A2
{
public class PrintName
{
public void intro()
{
Console.WriteLine ("My name is B");
}
}
}
}
输出结果:
My name is CG
My name is A
My name is B
在naemspace.cs 中
using System;
namespace CG
{
class Test
{
static void Main()
{
PrintName a = new PrintName();
a.intro();
}
}
}
在PrintName.cs
using System;
namespace CG
{
public class PrintName
{
public void intro()
{
Console.WriteLine("My Name is ABC");
}
}
}
csc naemspace.cs PrintName1.cs
naemspace.exe
csc /target:library PrintName1.cs
csc /reference:PrintName1.dll naemspace.cs
别名(Alias)
using System;
using System A=ParentNameSpace.ChildNameSpace

浙公网安备 33010602011771号