C# using

在C#中,我们使用 `using` 关键字在程序中导入外部资源(命名空间、类等)。例如:

// using System namespace
using System;

namespace Program {

  class Program1 {
    static void Main(string[] args) {
      Console.WriteLine("Hello World!");   
    }
  }
}

输出

Hello World!

在上面的示例中,请注意这一行

using System;

在这里,我们在程序中导入了 `System` 命名空间。这使我们可以直接使用 `System` 命名空间中的类。

因此,我们不必写出打印语句的完全限定名称。

// full print statement
System.Console.WriteLine("Hello World!");

// print statement with using System;
Console.WriteLine("Hello World!");

要了解有关命名空间的更多信息,请访问 C# 命名空间


C# using 用于创建别名

我们也可以通过C#中的 `using` 来创建别名。例如:

// creating alias for System.Console
using Programiz = System.Console;

namespace HelloWorld {

  class Program {
    static void Main(string[] args) {

      // using Programiz alias instead of System.Console
      Programiz.WriteLine("Hello World!");    
    }
  }
}

输出

Hello World!

在上面的程序中,我们为 `System.Console` 创建了一个别名。

using Programiz = System.Console;

这使得我们可以使用别名 `Programiz` 而不是 `System.Console`。

Programiz.WriteLine("Hello World!");

在这里,`Programiz` 的作用与 `System.Console` 相同。


C# using static 指令

在C#中,我们也可以将类导入到我们的程序中。导入这些类后,我们就可以使用类的静态成员(字段、方法)。

我们使用 `using static` 指令将类导入到我们的程序中。

示例:C# using static with System.Math

using System;

// using static directive
using static System.Math;

namespace Program {  

  class Program1  {  
    public static void Main(string[] args)  {  
       	 
      double n  = Sqrt(9);
      Console.WriteLine("Square root of 9 is " + n);  
      	 
    }  
  }  
}

输出

Square root of 9 is 3

在上面的示例中,请注意这一行:

using static System.Math;

这一行帮助我们直接访问 `Math` 类的方法。

double n = Sqrt(9);

我们直接使用了 `Sqrt()` 方法,而无需指定 `Math` 类。

如果我们不在程序中使用 `using static System.Math`,在使用 `Sqrt()` 时就必须包含类名 `Math`。例如:

using System; 
 
namespace Program {  

  class Program1 {  
    public static void Main(string[] args) {  

      // using the class name Math
      double n  = Math.Sqrt(9);
      Console.WriteLine("Square root of 9 is " + n);  
    }  
  }  
} 

输出

Square root of 9 is 3

在上面的示例中,请注意这一行:

double n = Math.Sqrt(9);

在这里,我们使用 `Math.Sqrt()` 来计算 **9** 的平方根。这是因为我们没有在此程序中导入 `System.Math`。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战