跳到主要内容

C# using语句

提示
  1. using关键字的基本用途:在C#中,using 关键字用于导入外部资源,如命名空间或类。例如,using System; 允许直接使用 System 命名空间中的类,简化代码书写。
  2. 使用using创建别名:可以使用 using 关键字为命名空间或类创建别名。例如,using Programiz = System.Console;System.Console 创建别名 Programiz,之后可以用 Programiz.WriteLine("Hello World!"); 代替 System.Console.WriteLine("Hello World!");
  3. 使用static指令导入类using static 指令用于导入类,允许直接访问类的静态成员。例如,using static System.Math; 允许直接使用 Math 类的静态方法,如 Sqrt,而无需在每次调用时指定类名。

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

// 使用 System 命名空间
using System;

namespace Program {

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

输出

Hello World!

在上面的示例中,注意这行代码

using System;

这里,我们正在将 System 命名空间导入到我们的程序中。这帮助我们直接使用 System 命名空间中的类。

此外,由于这个原因,我们不必写出完整的打印语句的名称。

// 完整的打印语句
System.Console.WriteLine("Hello World!");

// 使用 using System; 的打印语句
Console.WriteLine("Hello World!");

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

C# 使用 using 创建别名

我们还可以使用 C# 中的 using 创建别名。例如,

// 为 System.Console 创建别名
using Programiz = System.Console;

namespace HelloWorld {

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

// 使用 Programiz 别名代替 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# 使用 static 指令

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

我们使用 using static 指令在程序中导入类。

示例:C# 使用 static 与 System.Math

using System;

// 使用 static 指令
using static System.Math;

namespace Program {

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

double n = Sqrt(9);
Console.WriteLine("9 的平方根是 " + n);

}
}
}

输出

9 的平方根是 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) {

// 使用类名 Math
double n = Math.Sqrt(9);
Console.WriteLine("9 的平方根是 " + n);
}
}
}

输出

9 的平方根是 3

在上面的示例中,注意这行代码,

double n = Math.Sqrt(9);

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