char (c # 參考) char (C# reference)

charType 關鍵字是 System.Char 代表 Unicode utf-16 字元之 .net 結構類型的別名。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 運算元, 算術位邏輯 運算子會對對應的字元碼執行運算,並產生型別的結果 intMoreover, 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 escape 序列, \u 後面接著字元碼的四符號十六進位標記法。a Unicode escape sequence, which is \u followed by the four-symbol hexadecimal representation of a character code.
  • 十六進位的 escape 序列, \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 escape 序列的案例中,您必須指定全部四個十六進位數位。In the case of a Unicode escape sequence, you must specify all four hexadecimal digits. 也就是 \u006A 有效的 escape 序列,雖然 \u06A 和無效 \u6AThat is, \u006A is a valid escape sequence, while \u06A and \u6A are not valid.

在十六進位 escape 序列的情況下,您可以省略前置零。In the case of a hexadecimal escape sequence, you can omit the leading zeros. 也就是說, \x006A\x06A\x6A escape 序列是有效的,而且會對應到相同的字元。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.

沒有從其他類型到類型的隱含轉換 charThere 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