char(C# 参考)char (C# reference)

char 类型关键字是 .NET System.Char 结构类型的别名,它表示 Unicode UTF-16 字符。The char type keyword is an alias for the .NET System.Char structure type that represents a Unicode UTF-16 character.

类型Type 范围Range 大小Size .NET 类型.NET type
char U+0000 到 U+FFFFU+0000 to U+FFFF 16 位16 bit System.Char

char 类型的默认值为 \0,即 U+0000。The default value of the char type is \0, that is, U+0000.

char 类型支持比较相等增量减量运算符。The char type supports comparison, equality, increment, and decrement operators. 此外,对于 char 操作数,算数逻辑位运算符对相应的字符代码执行操作,并得出 int 类型的结果。Moreover, for char operands, arithmetic and bitwise logical operators perform an operation on the corresponding character codes and produce the result of the int type.

字符串类型将文本表示为 char 值的序列。The string type represents text as a sequence of char values.

文本Literals

可以使用以下命令指定 char 值:You can specify a char value with:

  • 字符文本。a character literal.
  • Unicode 转义序列,它是 \u 后跟字符代码的十六进制表示形式(四个符号)。a Unicode escape sequence, which is \u followed by the four-symbol hexadecimal representation of a character code.
  • 十六进制转义序列,它是 \x 后跟字符代码的十六进制表示形式。a hexadecimal escape sequence, which is \x followed by the hexadecimal representation of a character code.
var chars = new[]
{
    'j',
    '\u006A',
    '\x006A',
    (char)106,
};
Console.WriteLine(string.Join(" ", chars));  // output: j j j j

如前面的示例所示,你还可以将字符代码的值转换为相应的 char 值。As the preceding example shows, you can also cast the value of a character code into the corresponding char value.

备注

对于 Unicode 转义序列,必须指定全部四位十六进制值。In the case of a Unicode escape sequence, you must specify all four hexadecimal digits. 也就是说,\u006A 是一个有效的转义序列,而 \u06A\u6A 是无效的。That is, \u006A is a valid escape sequence, while \u06A and \u6A are not valid.

对于十六进制转义序列,可以省略前导零。In the case of a hexadecimal escape sequence, you can omit the leading zeros. 也就是说,\x006A\x06A\x6A 转义序列是有效的,并且对应于同一个字符。That is, the \x006A, \x06A, and \x6A escape sequences are valid and correspond to the same character.

转换Conversions

char 类型可隐式转换为以下整型类型:ushortintuintlongulongThe char type is implicitly convertible to the following integral types: ushort, int, uint, long, and ulong. 它也可以隐式转换为内置浮点数值类型:floatdoubledecimalIt's also implicitly convertible to the built-in floating-point numeric types: float, double, and decimal. 它可以显式转换为 sbytebyteshort 整型类型。It's explicitly convertible to sbyte, byte, and short integral types.

无法将其他类型隐式转换为 char 类型。There are no implicit conversions from other types to the char type. 但是,任何整型浮点数值类型都可显式转换为 charHowever, any integral or floating-point numeric type is explicitly convertible to char.

C# 语言规范C# language specification

有关详细信息,请参阅 C# 语言规范整型类型部分。For more information, see the Integral types section of the C# language specification.

请参阅See also