C# 从0到实战 命名空间

2023-06-15,,

什么是命名空间

命名空间是C#为了解决类名冲突而产生的一种方案,通过特定的前缀来标识一个类,使得编程者可以在自己的命名空间中自由使用各种类名,这很类似于Java中的包。

一般新手学习C#都会使用一个 console 类,它就是属于system 中的。

namespace System;

internal class DemoClass
{
public static void main()
{
Console.WriteLine();
}
}

C# 10更新后的命名空间

用过Java的人都知道,Java的包只要在程序的第一行声明包名即可,无需大括号,这大大方便了多个类文件的编写。而在10.0以前,C#都得用一个大括号包裹住一个类,带来了不便;所以从10.0以后,也可以像Java一样的写法声明一个命名空间中的类。

namespace SampleNamespace;

class AnotherSampleClass
{
public void AnotherSampleMethod()
{
System.Console.WriteLine(
"SampleMethod inside SampleNamespace");
}
}
namespace SampleNamespace;  //和AnotherSampleClass包含在同一个命名空间中 

class AnotherSampleClass2 {

  public void AnotherSampleMethod2()
  {
   System.Console.WriteLine( "SampleMethod inside SampleNamespace");
  }
}

上面代码中的两个类都是属于命名空间 SampleNameSpace中的。

命名空间的使用

我们在之前已经声明了一个命名空间,当我们需要调用其中的类或者静态方法时,可以使用以下形式调用:

//....
using SampleNamespace;
//.... SampleNamespace.AnotherSampleClass o = new SampleNamespace.AnotherSampleClass(); //调用形式1 AnotherSampleClass o = new AnotherSampleClass(); //调用形式2

  

C# 从0到实战 命名空间的相关教程结束。

《C# 从0到实战 命名空间.doc》

下载本文的Word格式文档,以方便收藏与打印。