C# 命名空间(NameSpace)

来源:互联网 发布:大数据概念股龙头股票 编辑:程序博客网 时间:2024/05/16 18:32

命名空间的设计目的是提供一种让一组名称与其他名称分隔的方式。在一个命名空间中声明的类的名称与另一个命名空间中声明的相同类的名称不冲突。

定义命名空间

命名空间的定义是以关键字namespace开始,后跟命名空间的名称,如下所示

namespace namespace_name

{

//代码声明

}

为了调用支持命名空间版本的函数或变量,会把命名空间的名称置于前面,如下所示:

namespace_name.ite_name;

下面的程序示例了命名空间的用法:

//C#命名空间的语法using System;namespace first_space{    class namespace_cl    {        public void func()        {            Console.WriteLine("the first namespace");        }    }}namespace second_space{    class namespace_cl    {        public void func()        {            Console.WriteLine("the second namespace");        }    }}class TestClass{    static void Mian(string[] args)    {        first_space.namespace_cl fc = new first_space.namespace_cl();        second_space.namespace_cl sc = new second_space.namespace_cl();        fc.func();        sc.func();        Console.ReadKey();    }}


using关键字

using关键字表明程序使用的是给定命名空中的名称。例如,我们在程序中使用System命名空间,其中定义了类Console。我们可以只写:

Console.WriteLine("Hello World“);

我们也可以写完全限定名称,如下:

System.Console.WriteLine(”Hello World“);

同样的也可以使用using命名空间指令,这样在使用的时候就不用在前面加上命名空间名称。该指令告诉编译器随后的代码使用了指定命名空间中的名称。下面的代码演示了命名空间的应用。

//C#中using命令的使用using System;using first_space;using second_space;namespace first_space{    class abc    {        public void func()        {            Console.WriteLine("the first namespace");        }    }}namespace second_space{    class edf    {        public void func()        {            Console.WriteLine("the second namespace");        }    }}class TestClass{    static void Mian(string[] args)    {        abc fc = new abc();        edf sc = new edf();        fc.func();        sc.func();        Console.ReadKey();    }}


嵌套命名空间

命名空间可以被嵌套,即可以在一个命名空间内定义另一个命名空间

我们可以使用(.)运算符来访问嵌套的命名空间的成员,如下所示:

//C#嵌套命名空间using System;using SomeNameSpace;using SomeNameSpace.Nested;namespace SomeNameSpace{    public class Myclass    {        static void Mian()        {            Console.WriteLine("In SomeNameSpace");            Nested.NestedNameSpaceClass.SayHello();        }    }    //内嵌命名空间    namespace Nested    {        public class NestedNameSpaceClass        {            public static void SayHello()            {                Console.WriteLine("In Nested");            }        }    }}



原创粉丝点击