global using System.Text;
任何 global using
指令都必须在该源文件中的任何非全局 using
指令之前,并且不得放置在 namespace
中。 这样做会分别导致生成 CS8915 和 CS8914。
此外,static global using
指令不能引用文件本地类型。
别名限定符
别名限定符 ::
位于命名空间别名之前,或位于 global
别名之后。 如果在 .
应该用于分隔完全限定名称的元素的情况下使用 ::
,编译器会发出 CS0431、CS0432、CS0687、*CS7000 或 CS8083 之一。
在所有情况下,请将 ::
替换为 .
分隔符。
此外,如果定义名为 global
的别名,编译器会发出 CS0440。 global
别名始终引用全局命名空间。 为它声明别名不起作用,应选择其他名称作为别名。
可以使用 using
指令声明命名空间或类型的别名:
using JSON = System.Text.Json;
using ValueMap = System.Collections.Generic.Dictionary<string, decimal>;
using TimedData = (System.DateTime timeRecorded, decimal value);
应尝试为别名创建唯一名称,即前面示例中 =
符号左侧的名称。 使用已映射到某个类型(例如 Object
)或命名空间 (System
) 的名称会导致 CS0576 或 CS1537。
有关 using 别名的限制
在 C# 12 之前,该语言对创建类型声明的别名的 using
指令施加了以下限制:
不能使用 using static
指令创建别名:
using static con = System.Console;
using static unsafe ip = int*;
从 C# 12 开始,引入了以下限制:
不能在 using 别名中使用 in
、ref
或 out
修饰符:
// All these are invalid
using RefInt = ref int;
using OutInt = out int;
using InInt = in int;
unsafe using
指令必须指定别名或 static using
:
// Elsewhere:
public namespace UnsafeExamples
public unsafe static class UnsafeType
// ...
// Using directives:
using unsafe IntPointer = int*;
using static unsafe UnsafeExamples.UnsafeType;
using unsafe UnsafeExamples; // not allowed
不能为可为 null 的引用类型创建别名:
using NullableInt = System.Int32?; // Allowed
using NullableString = System.String?; // Not allowed