Char 结构

定义

将字符表示为 UTF-16 代码单位。Represents a character as a UTF-16 code unit.

public value class Char : IComparable, IComparable<char>, IConvertible, IEquatable<char>
public value class Char : IComparable, IConvertible
public value class Char : IComparable, IComparable<char>, IEquatable<char>
public struct Char : IComparable, IComparable<char>, IConvertible, IEquatable<char>
[System.Serializable]
public struct Char : IComparable, IConvertible
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public struct Char : IComparable, IComparable<char>, IConvertible, IEquatable<char>
public struct Char : IComparable, IComparable<char>, IEquatable<char>
type char = struct
    interface IConvertible
[<System.Serializable>]
type char = struct
    interface IConvertible
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type char = struct
    interface IConvertible
type char = struct
Public Structure Char
Implements IComparable, IComparable(Of Char), IConvertible, IEquatable(Of Char)
Public Structure Char
Implements IComparable, IConvertible
Public Structure Char
Implements IComparable, IComparable(Of Char), IEquatable(Of Char)
继承
属性
实现

示例

下面的代码示例演示中的一些方法 CharThe following code example demonstrates some of the methods in Char.

using namespace System;
int main()
{
   char chA = 'A';
   char ch1 = '1';
   String^ str =  "test string";
   Console::WriteLine( chA.CompareTo( 'B' ) ); // Output: "-1" (meaning 'A' is 1 less than 'B')
   Console::WriteLine( chA.Equals( 'A' ) ); // Output: "True"
   Console::WriteLine( Char::GetNumericValue( ch1 ) ); // Output: "1"
   Console::WriteLine( Char::IsControl( '\t' ) ); // Output: "True"
   Console::WriteLine( Char::IsDigit( ch1 ) ); // Output: "True"
   Console::WriteLine( Char::IsLetter( ',' ) ); // Output: "False"
   Console::WriteLine( Char::IsLower( 'u' ) ); // Output: "True"
   Console::WriteLine( Char::IsNumber( ch1 ) ); // Output: "True"
   Console::WriteLine( Char::IsPunctuation( '.' ) ); // Output: "True"
   Console::WriteLine( Char::IsSeparator( str, 4 ) ); // Output: "True"
   Console::WriteLine( Char::IsSymbol( '+' ) ); // Output: "True"
   Console::WriteLine( Char::IsWhiteSpace( str, 4 ) ); // Output: "True"
   Console::WriteLine( Char::Parse(  "S" ) ); // Output: "S"
   Console::WriteLine( Char::ToLower( 'M' ) ); // Output: "m"
   Console::WriteLine( 'x' ); // Output: "x"
}
using System;

public class CharStructureSample
{
    public static void Main()
    {
        char chA = 'A';
        char ch1 = '1';
        string str = "test string";

        Console.WriteLine(chA.CompareTo('B'));          //-----------  Output: "-1" (meaning 'A' is 1 less than 'B')
        Console.WriteLine(chA.Equals('A'));             //-----------  Output: "True"
        Console.WriteLine(Char.GetNumericValue(ch1));   //-----------  Output: "1"
        Console.WriteLine(Char.IsControl('\t'));        //-----------  Output: "True"
        Console.WriteLine(Char.IsDigit(ch1));           //-----------  Output: "True"
        Console.WriteLine(Char.IsLetter(','));          //-----------  Output: "False"
        Console.WriteLine(Char.IsLower('u'));           //-----------  Output: "True"
        Console.WriteLine(Char.IsNumber(ch1));          //-----------  Output: "True"
        Console.WriteLine(Char.IsPunctuation('.'));     //-----------  Output: "True"
        Console.WriteLine(Char.IsSeparator(str, 4));    //-----------  Output: "True"
        Console.WriteLine(Char.IsSymbol('+'));          //-----------  Output: "True"
        Console.WriteLine(Char.IsWhiteSpace(str, 4));   //-----------  Output: "True"
        Console.WriteLine(Char.Parse("S"));             //-----------  Output: "S"
        Console.WriteLine(Char.ToLower('M'));           //-----------  Output: "m"
        Console.WriteLine('x'.ToString());              //-----------  Output: "x"
    }
}
Module CharStructure

    Public Sub Main()

        Dim chA As Char
        chA = "A"c
        Dim ch1 As Char
        ch1 = "1"c
        Dim str As String
        str = "test string"

        Console.WriteLine(chA.CompareTo("B"c))          ' Output: "-1" (meaning 'A' is 1 less than 'B')
        Console.WriteLine(chA.Equals("A"c))             ' Output: "True"
        Console.WriteLine(Char.GetNumericValue(ch1))    ' Output: "1"
        Console.WriteLine(Char.IsControl(Chr(9)))       ' Output: "True"
        Console.WriteLine(Char.IsDigit(ch1))            ' Output: "True"
        Console.WriteLine(Char.IsLetter(","c))          ' Output: "False"
        Console.WriteLine(Char.IsLower("u"c))           ' Output: "True"
        Console.WriteLine(Char.IsNumber(ch1))           ' Output: "True"
        Console.WriteLine(Char.IsPunctuation("."c))     ' Output: "True"
        Console.WriteLine(Char.IsSeparator(str, 4))     ' Output: "True"
        Console.WriteLine(Char.IsSymbol("+"c))          ' Output: "True"
        Console.WriteLine(Char.IsWhiteSpace(str, 4))    ' Output: "True"
        Console.WriteLine(Char.Parse("S"))              ' Output: "S"
        Console.WriteLine(Char.ToLower("M"c))           ' Output: "m"
        Console.WriteLine("x"c.ToString())              ' Output: "x"

    End Sub

End Module

注解

.NET 使用 Char 结构来通过使用 utf-16 编码来表示 Unicode 码位。.NET uses the Char structure to represent Unicode code points by using UTF-16 encoding. 对象的值 Char 是其16位数字 (序号) 值。The value of a Char object is its 16-bit numeric (ordinal) value.

如果你不熟悉 Unicode、标量值、代码点、代理项对、UTF-16 和 Rune 类型,请参阅 .net 中的字符编码简介If you aren't familiar with Unicode, scalar values, code points, surrogate pairs, UTF-16, and the Rune type, see Introduction to character encoding in .NET.

以下部分检查 Char 对象与字符之间的关系,并讨论使用实例执行的一些常见任务 CharThe following sections examine the relationship between a Char object and a character and discuss some common tasks performed with Char instances. 建议你考虑 Rune .Net Core 3.0 中引入的类型,作为执行某些任务的替代方法 CharWe recommend that you consider the Rune type, introduced in .NET Core 3.0, as an alternative to Char for performing some of these tasks.

Char 对象、Unicode 字符和字符串Char objects, Unicode characters, and strings

String对象是表示文本字符串的结构的有序集合 CharA String object is a sequential collection of Char structures that represents a string of text. 大多数 Unicode 字符可以由单个 Char 对象表示,但是编码为基字符、代理项对和/或组合字符序列的字符由多个 Char 对象表示。Most Unicode characters can be represented by a single Char object, but a character that is encoded as a base character, surrogate pair, and/or combining character sequence is represented by multiple Char objects. 出于此原因, Char 对象中的结构 String 不一定等效于单个 Unicode 字符。For this reason, a Char structure in a String object is not necessarily equivalent to a single Unicode character.

在以下情况下,多个16位代码单元用于表示单个 Unicode 字符:Multiple 16-bit code units are used to represent single Unicode characters in the following cases:

  • 字形,可能包含单个字符或后跟一个或多个组合字符的基本字符。Glyphs, which may consist of a single character or of a base character followed by one or more combining characters. 例如,字符ä由 Char 其代码单元为 u + 0061 的对象后跟 Char 其代码单元为 u + 0308 的对象表示。For example, the character ä is represented by a Char object whose code unit is U+0061 followed by a Char object whose code unit is U+0308. (字符ä还可以由 Char 代码单位为 U + 00E4 的单个对象定义。 ) 下面的示例说明了字符ä包含两个 Char 对象。(The character ä can also be defined by a single Char object that has a code unit of U+00E4.) The following example illustrates that the character ä consists of two Char objects.

    using System;
    using System.IO;
    
    public class Example
    {
       public static void Main()
       {
          StreamWriter sw = new StreamWriter("chars1.txt");
          char[] chars = { '\u0061', '\u0308' };
          string strng = new String(chars);
          sw.WriteLine(strng);
          sw.Close();
       }
    }
    // The example produces the following output:
    //       ä
    
    Imports System.IO
    
    Module Example
       Public Sub Main()
          Dim sw As New StreamWriter("chars1.txt")
          Dim chars() As Char = { ChrW(&h0061), ChrW(&h0308) }
          Dim strng As New String(chars)
          sw.WriteLine(strng) 
          sw.Close()
       End Sub
    End Module
    ' The example produces the following output:
    '       ä
    
  • Unicode 基本多语言平面 (BMP) 以外的字符。Characters outside the Unicode Basic Multilingual Plane (BMP). Unicode 除了支持表示平面0的 BMP 外,还支持十六个平面。Unicode supports sixteen planes in addition to the BMP, which represents plane 0. Unicode 码位由包含平面的21位值用 UTF-32 表示。A Unicode code point is represented in UTF-32 by a 21-bit value that includes the plane. 例如,U + 1D160 表示音乐符号第8说明字符。For example, U+1D160 represents the MUSICAL SYMBOL EIGHTH NOTE character. 由于 UTF-16 编码只有16位,因此 BMP 外的字符由 UTF-16 中的代理项对表示。Because UTF-16 encoding has only 16 bits, characters outside the BMP are represented by surrogate pairs in UTF-16. 下面的示例说明了32等效于 U + 1D160,即音乐符号第8注释字符,为 U + D834 U + DD60。The following example illustrates that the UTF-32 equivalent of U+1D160, the MUSICAL SYMBOL EIGHTH NOTE character, is U+D834 U+DD60. U + D834 为高代理项;高代理项范围是从 U + D800 到 U + DBFF。U+D834 is the high surrogate; high surrogates range from U+D800 through U+DBFF. U + DD60 是低代理项;低代理项范围是从 U + DC00 到 U + DFFF。U+DD60 is the low surrogate; low surrogates range from U+DC00 through U+DFFF.

    using System;
    using System.IO;
    
    public class Example
    {
       public static void Main()
       {
          StreamWriter sw = new StreamWriter(@".\chars2.txt");
          int utf32 = 0x1D160;
          string surrogate = Char.ConvertFromUtf32(utf32);
          sw.WriteLine("U+{0:X6} UTF-32 = {1} ({2}) UTF-16",
                       utf32, surrogate, ShowCodePoints(surrogate));
          sw.Close();
       }
    
       private static string ShowCodePoints(string value)
       {
          string retval = null;
          foreach (var ch in value)
             retval += String.Format("U+{0:X4} ", Convert.ToUInt16(ch));
    
          return retval.Trim();
       }
    }
    // The example produces the following output:
    //       U+01D160 UTF-32 = ð (U+D834 U+DD60) UTF-16
    
    Imports System.IO
    
    Module Example
       Public Sub Main()
          Dim sw As New StreamWriter(".\chars2.txt")
          Dim utf32 As Integer = &h1D160
          Dim surrogate As String = Char.ConvertFromUtf32(utf32)
          sw.WriteLine("U+{0:X6} UTF-32 = {1} ({2}) UTF-16", 
                       utf32, surrogate, ShowCodePoints(surrogate))
          sw.Close()                    
       End Sub
    
       Private Function ShowCodePoints(value As String) As String
          Dim retval As String = Nothing
          For Each ch In value
             retval += String.Format("U+{0:X4} ", Convert.ToUInt16(ch))
          Next
          Return retval.Trim()
       End Function
    End Module
    ' The example produces the following output:
    '       U+01D160 UTF-32 = ð (U+D834 U+DD60) UTF-16
    

字符和字符类别Characters and character categories

每个 Unicode 字符或有效代理项对属于一个 Unicode 类别。Each Unicode character or valid surrogate pair belongs to a Unicode category. 在 .NET Framework 中,Unicode 类别由枚举的成员表示, UnicodeCategory 并包含诸如 UnicodeCategory.CurrencySymbolUnicodeCategory.LowercaseLetter 和之类的值 UnicodeCategory.SpaceSeparatorIn the .NET Framework, Unicode categories are represented by members of the UnicodeCategory enumeration and include values such as UnicodeCategory.CurrencySymbol, UnicodeCategory.LowercaseLetter, and UnicodeCategory.SpaceSeparator, for example.

若要确定字符的 Unicode 类别,请调用 GetUnicodeCategory 方法。To determine the Unicode category of a character, call the GetUnicodeCategory method. 例如,下面的示例调用 GetUnicodeCategory 以显示字符串中每个字符的 Unicode 类别。For example, the following example calls the GetUnicodeCategory to display the Unicode category of each character in a string. 仅当实例中没有代理项对时,此示例才能正常运行 StringThe example works correctly only if there are no surrogate pairs in the String instance.

using System;
using System.Globalization;

class Example
{
   public static void Main()
   {
      // Define a string with a variety of character categories.
      String s = "The red car drove down the long, narrow, secluded road.";
      // Determine the category of each character.
      foreach (var ch in s)
         Console.WriteLine("'{0}': {1}", ch, Char.GetUnicodeCategory(ch));
   }
}
// The example displays the following output:
//      'T': UppercaseLetter
//      'h': LowercaseLetter
//      'e': LowercaseLetter
//      ' ': SpaceSeparator
//      'r': LowercaseLetter
//      'e': LowercaseLetter
//      'd': LowercaseLetter
//      ' ': SpaceSeparator
//      'c': LowercaseLetter
//      'a': LowercaseLetter
//      'r': LowercaseLetter
//      ' ': SpaceSeparator
//      'd': LowercaseLetter
//      'r': LowercaseLetter
//      'o': LowercaseLetter
//      'v': LowercaseLetter
//      'e': LowercaseLetter
//      ' ': SpaceSeparator
//      'd': LowercaseLetter
//      'o': LowercaseLetter
//      'w': LowercaseLetter
//      'n': LowercaseLetter
//      ' ': SpaceSeparator
//      't': LowercaseLetter
//      'h': LowercaseLetter
//      'e': LowercaseLetter
//      ' ': SpaceSeparator
//      'l': LowercaseLetter
//      'o': LowercaseLetter
//      'n': LowercaseLetter
//      'g': LowercaseLetter
//      ',': OtherPunctuation
//      ' ': SpaceSeparator
//      'n': LowercaseLetter
//      'a': LowercaseLetter
//      'r': LowercaseLetter
//      'r': LowercaseLetter
//      'o': LowercaseLetter
//      'w': LowercaseLetter
//      ',': OtherPunctuation
//      ' ': SpaceSeparator
//      's': LowercaseLetter
//      'e': LowercaseLetter
//      'c': LowercaseLetter
//      'l': LowercaseLetter
//      'u': LowercaseLetter
//      'd': LowercaseLetter
//      'e': LowercaseLetter
//      'd': LowercaseLetter
//      ' ': SpaceSeparator
//      'r': LowercaseLetter
//      'o': LowercaseLetter
//      'a': LowercaseLetter
//      'd': LowercaseLetter
//      '.': OtherPunctuation
Imports System.Globalization

Module Example
   Public Sub Main()
      ' Define a string with a variety of character categories.
      Dim s As String = "The car drove down the narrow, secluded road."
      ' Determine the category of each character.
      For Each ch In s
         Console.WriteLine("'{0}': {1}", ch, Char.GetUnicodeCategory(ch)) 
      Next
   End Sub
End Module
' The example displays the following output:
'       'T': UppercaseLetter
'       'h': LowercaseLetter
'       'e': LowercaseLetter
'       ' ': SpaceSeparator
'       'r': LowercaseLetter
'       'e': LowercaseLetter
'       'd': LowercaseLetter
'       ' ': SpaceSeparator
'       'c': LowercaseLetter
'       'a': LowercaseLetter
'       'r': LowercaseLetter
'       ' ': SpaceSeparator
'       'd': LowercaseLetter
'       'r': LowercaseLetter
'       'o': LowercaseLetter
'       'v': LowercaseLetter
'       'e': LowercaseLetter
'       ' ': SpaceSeparator
'       'd': LowercaseLetter
'       'o': LowercaseLetter
'       'w': LowercaseLetter
'       'n': LowercaseLetter
'       ' ': SpaceSeparator
'       't': LowercaseLetter
'       'h': LowercaseLetter
'       'e': LowercaseLetter
'       ' ': SpaceSeparator
'       'l': LowercaseLetter
'       'o': LowercaseLetter
'       'n': LowercaseLetter
'       'g': LowercaseLetter
'       ',': OtherPunctuation
'       ' ': SpaceSeparator
'       'n': LowercaseLetter
'       'a': LowercaseLetter
'       'r': LowercaseLetter
'       'r': LowercaseLetter
'       'o': LowercaseLetter
'       'w': LowercaseLetter
'       ',': OtherPunctuation
'       ' ': SpaceSeparator
'       's': LowercaseLetter
'       'e': LowercaseLetter
'       'c': LowercaseLetter
'       'l': LowercaseLetter
'       'u': LowercaseLetter
'       'd': LowercaseLetter
'       'e': LowercaseLetter
'       'd': LowercaseLetter
'       ' ': SpaceSeparator
'       'r': LowercaseLetter
'       'o': LowercaseLetter
'       'a': LowercaseLetter
'       'd': LowercaseLetter
'       '.': OtherPunctuation

在内部,对于 ASCII 范围外的字符 (U + 0000 到 U + 00FF) ,该 GetUnicodeCategory 方法取决于类报告的 Unicode 类别 CharUnicodeInfoInternally, for characters outside the ASCII range (U+0000 through U+00FF), the GetUnicodeCategory method depends on Unicode categories reported by the CharUnicodeInfo class. 从开始,将根据 .NET Framework 4.6.2.NET Framework 4.6.2 Unicode 标准版本 8.0.0对 unicode 字符进行分类。Starting with the .NET Framework 4.6.2.NET Framework 4.6.2, Unicode characters are classified based on The Unicode Standard, Version 8.0.0. 在的 .NET Framework 版本中,将 .NET Framework 4.NET Framework 4 .NET Framework 4.6.1.NET Framework 4.6.1 根据 Unicode 标准版本 6.3.0对它们进行分类。In versions of the .NET Framework from the .NET Framework 4.NET Framework 4 to the .NET Framework 4.6.1.NET Framework 4.6.1, they are classified based on The Unicode Standard, Version 6.3.0.

字符和文本元素Characters and text elements

因为单个字符可由多个对象表示 Char ,所以,处理单个对象并不总是有意义的 CharBecause a single character can be represented by multiple Char objects, it is not always meaningful to work with individual Char objects. 例如,下面的示例将表示爱琴大学数字0到9的 Unicode 码位转换为 UTF-16 编码的代码单元。For instance, the following example converts the Unicode code points that represent the Aegean numbers zero through 9 to UTF-16 encoded code units. 因为它错误地 Char 使对象具有字符,所以它不准确地报告生成的字符串具有20个字符。Because it erroneously equates Char objects with characters, it inaccurately reports that the resulting string has 20 characters.

using System;

public class Example
{
   public static void Main()
   {
      string result = String.Empty;
      for (int ctr = 0x10107; ctr <= 0x10110; ctr++)  // Range of Aegean numbers.
         result += Char.ConvertFromUtf32(ctr);

      Console.WriteLine("The string contains {0} characters.", result.Length);
   }
}
// The example displays the following output:
//     The string contains 20 characters.
Module Example
   Public Sub Main()
      Dim result As String = String.Empty
      For ctr As Integer = &h10107 To &h10110     ' Range of Aegean numbers.
         result += Char.ConvertFromUtf32(ctr)
      Next         
      Console.WriteLine("The string contains {0} characters.", result.Length) 
   End Sub
End Module
' The example displays the following output:
'     The string contains 20 characters.

您可以执行以下操作来避免假设 Char 对象表示单个字符。You can do the following to avoid the assumption that a Char object represents a single character.

  • 您可以完整地处理 String 对象,而不是使用其各个字符来表示和分析语言内容。You can work with a String object in its entirety instead of working with its individual characters to represent and analyze linguistic content.

  • 可使用, String.EnumerateRunes 如以下示例中所示:You can use String.EnumerateRunes as shown in the following example:

    int CountLetters(string s)
    {
        int letterCount = 0;
    
        foreach (Rune rune in s.EnumerateRunes())
        {
            if (Rune.IsLetter(rune))
            { letterCount++; }
        }
    
        return letterCount;
    }
    
  • 您可以使用 StringInfo 类来处理文本元素,而不是单个 Char 对象。You can use the StringInfo class to work with text elements instead of individual Char objects. 下面的示例使用 StringInfo 对象计算字符串中的文本元素数,该字符串包含从零到9的爱琴大学数字。The following example uses the StringInfo object to count the number of text elements in a string that consists of the Aegean numbers zero through nine. 由于它将代理项对视为单个字符,因此它会正确地报告该字符串包含十个字符。Because it considers a surrogate pair a single character, it correctly reports that the string contains ten characters.

    using System;
    using System.Globalization;
    
    public class Example
    {
       public static void Main()
       {
          string result = String.Empty;
          for (int ctr = 0x10107; ctr <= 0x10110; ctr++)  // Range of Aegean numbers.
             result += Char.ConvertFromUtf32(ctr);
    
          StringInfo si = new StringInfo(result);
          Console.WriteLine("The string contains {0} characters.",
                            si.LengthInTextElements);
       }
    }
    // The example displays the following output:
    //       The string contains 10 characters.
    
    Imports System.Globalization
    
    Module Example
       Public Sub Main()
          Dim result As String = String.Empty
          For ctr As Integer = &h10107 To &h10110     ' Range of Aegean numbers.
             result += Char.ConvertFromUtf32(ctr)
          Next         
          Dim si As New StringInfo(result)
          Console.WriteLine("The string contains {0} characters.", si.LengthInTextElements) 
       End Sub
    End Module
    ' The example displays the following output:
    '       The string contains 10 characters.
    
  • 如果字符串包含具有一个或多个组合字符的基字符,则可以调用方法将 String.Normalize 子字符串转换为单个 utf-16 编码的代码单元。If a string contains a base character that has one or more combining characters, you can call the String.Normalize method to convert the substring to a single UTF-16 encoded code unit. 下面的示例调用 String.Normalize 方法,将基本字符 u + 0061 转换 (拉丁文小写字母 A) 并结合字符 u + 0308 (将分音符) 组合到 U + 00E4 (带有分音符) 的拉丁文小写字母 A。The following example calls the String.Normalize method to convert the base character U+0061 (LATIN SMALL LETTER A) and combining character U+0308 (COMBINING DIAERESIS) to U+00E4 (LATIN SMALL LETTER A WITH DIAERESIS).

    using System;
    
    public class Example
    {
       public static void Main()
       {
          string combining = "\u0061\u0308";
          ShowString(combining);
    
          string normalized = combining.Normalize();
          ShowString(normalized);
       }
    
       private static void ShowString(string s)
       {
          Console.Write("Length of string: {0} (", s.Length);
          for (int ctr = 0; ctr < s.Length; ctr++) {
             Console.Write("U+{0:X4}", Convert.ToUInt16(s[ctr]));
             if (ctr != s.Length - 1) Console.Write(" ");
          }
          Console.WriteLine(")\n");
       }
    }
    // The example displays the following output:
    //       Length of string: 2 (U+0061 U+0308)
    //
    //       Length of string: 1 (U+00E4)
    
    Module Example
       Public Sub Main()
          Dim combining As String = ChrW(&h0061) + ChrW(&h0308)
          ShowString(combining)
          
          Dim normalized As String = combining.Normalize()
          ShowString(normalized)
       End Sub
       
       Private Sub ShowString(s As String)
          Console.Write("Length of string: {0} (", s.Length)
          For ctr As Integer = 0 To s.Length - 1
             Console.Write("U+{0:X4}", Convert.ToUInt16(s(ctr)))
             If ctr <> s.Length - 1 Then Console.Write(" ")
          Next 
          Console.WriteLine(")")
          Console.WriteLine()
       End Sub
    End Module
    ' The example displays the following output:
    '       Length of string: 2 (U+0061 U+0308)
    '       
    '       Length of string: 1 (U+00E4)
    

常见操作Common operations

Char 结构提供了比较对象的方法 Char ,将当前对象的值转换 Char 为另一种类型的对象,并确定对象的 Unicode 类别 CharThe Char structure provides methods to compare Char objects, convert the value of the current Char object to an object of another type, and determine the Unicode category of a Char object:

要执行此操作To do this 使用这些 System.Char 方法Use these System.Char methods
比较 Char 对象Compare Char objects CompareToEqualsCompareTo and Equals
将码位转换为字符串Convert a code point to a string ConvertFromUtf32

另请参阅 Rune 类型。See also the Rune type.
Char 对象或代理项对转换 Char 为码位Convert a Char object or a surrogate pair of Char objects to a code point 对于单个字符: Convert.ToInt32(Char)For a single character: Convert.ToInt32(Char)

对于代理项对或字符串中的字符: Char.ConvertToUtf32For a surrogate pair or a character in a string: Char.ConvertToUtf32

另请参阅 Rune 类型。See also the Rune type.
获取字符的 Unicode 类别Get the Unicode category of a character GetUnicodeCategory

另请参阅 Rune.GetUnicodeCategorySee also Rune.GetUnicodeCategory.
确定字符是否在特定的 Unicode 类别中,如数字、字母、标点、控制字符等Determine whether a character is in a particular Unicode category such as digit, letter, punctuation, control character, and so on IsControlIsDigitIsHighSurrogateIsLetterIsLetterOrDigitIsLowerIsLowSurrogateIsNumber IsPunctuation IsSeparator IsSurrogate IsSurrogatePair IsSymbol IsUpper 、、、、、、和 IsWhiteSpaceIsControl, IsDigit, IsHighSurrogate, IsLetter, IsLetterOrDigit, IsLower, IsLowSurrogate, IsNumber, IsPunctuation, IsSeparator, IsSurrogate, IsSurrogatePair, IsSymbol, IsUpper, and IsWhiteSpace

另请参阅类型上的对应方法 RuneSee also corresponding methods on the Rune type.
Char 表示数字的对象转换为数值类型Convert a Char object that represents a number to a numeric value type GetNumericValue

另请参阅 Rune.GetNumericValueSee also Rune.GetNumericValue.
将字符串中的字符转换为 Char 对象Convert a character in a string into a Char object ParseTryParseParse and TryParse
Char 对象转换为 String 对象Convert a Char object to a String object ToString
更改对象的大小写 CharChange the case of a Char object ToLowerToLowerInvariantToUpperToUpperInvariantToLower, ToLowerInvariant, ToUpper, and ToUpperInvariant

另请参阅类型上的对应方法 RuneSee also corresponding methods on the Rune type.

Char 值和互操作Char values and interop

当托管 Char 类型(表示为 UNICODE utf-16 编码的代码单元)被传递到非托管代码时,互操作封送拆收器默认情况下将字符集转换为 ANSI。When a managed Char type, which is represented as a Unicode UTF-16 encoded code unit, is passed to unmanaged code, the interop marshaler converts the character set to ANSI by default. 可以将属性应用 DllImportAttribute 到平台调用声明,并将 StructLayoutAttribute 特性应用于 COM 互操作声明,以控制封送 Char 类型使用的字符集。You can apply the DllImportAttribute attribute to platform invoke declarations and the StructLayoutAttribute attribute to a COM interop declaration to control which character set a marshaled Char type uses.

字段

MaxValue

表示 Char 的最大可能值。Represents the largest possible value of a Char. 此字段为常数。This field is constant.

MinValue

表示 Char 的最小可能值。Represents the smallest possible value of a Char. 此字段为常数。This field is constant.

方法

CompareTo(Char)

将此实例与指定的 Char 对象进行比较,并指示此实例在排序顺序中是位于指定的 Char 对象之前、之后还是与其出现在同一位置。Compares this instance to a specified Char object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified Char object.

CompareTo(Object)

将此实例与指定的对象进行比较,并指示此实例在排序顺序中是位于指定的 Object 之前、之后还是与其出现在同一位置。Compares this instance to a specified object and indicates whether this instance precedes, follows, or appears in the same position in the sort order as the specified Object.

ConvertFromUtf32(Int32)

将指定的 Unicode 码位转换为 UTF-16 编码字符串。Converts the specified Unicode code point into a UTF-16 encoded string.

ConvertToUtf32(Char, Char)

将 UTF-16 编码的代理项对的值转换为 Unicode 码位。Converts the value of a UTF-16 encoded surrogate pair into a Unicode code point.

ConvertToUtf32(String, Int32)

将字符串中指定位置的 UTF-16 编码字符或代理项对的值转换为 Unicode 码位。Converts the value of a UTF-16 encoded character or surrogate pair at a specified position in a string into a Unicode code point.

Equals(Char)

返回一个值,该值指示此实例是否等于指定的 Char 对象。Returns a value that indicates whether this instance is equal to the specified Char object.

Equals(Object)

返回一个值,该值指示此实例是否与指定的对象相等。Returns a value that indicates whether this instance is equal to a specified object.

GetHashCode()

返回此实例的哈希代码。Returns the hash code for this instance.

GetNumericValue(Char)

将指定的数字 Unicode 字符转换为双精度浮点数。Converts the specified numeric Unicode character to a double-precision floating point number.

GetNumericValue(String, Int32)

将指定字符串中位于指定位置的数字 Unicode 字符转换为双精度浮点数。Converts the numeric Unicode character at the specified position in a specified string to a double-precision floating point number.

GetTypeCode()

返回值类型 TypeCodeCharReturns the TypeCode for value type Char.

GetUnicodeCategory(Char)

将指定的 Unicode 字符分类到由一个 UnicodeCategory 值标识的组中。Categorizes a specified Unicode character into a group identified by one of the UnicodeCategory values.

GetUnicodeCategory(String, Int32)

将指定字符串中位于指定位置的字符分类到由一个 UnicodeCategory 值标识的组中。Categorizes the character at the specified position in a specified string into a group identified by one of the UnicodeCategory values.

IsControl(Char)

指示指定的 Unicode 字符是否属于控制字符类别。Indicates whether the specified Unicode character is categorized as a control character.

IsControl(String, Int32)

指示指定字符串中位于指定位置处的字符是否属于控制字符类别。Indicates whether the character at the specified position in a specified string is categorized as a control character.

IsDigit(Char)

指示指定的 Unicode 字符是否属于十进制数字类别。Indicates whether the specified Unicode character is categorized as a decimal digit.

IsDigit(String, Int32)

指示指定字符串中位于指定位置处的字符是否属于十进制数字类别。Indicates whether the character at the specified position in a specified string is categorized as a decimal digit.

IsHighSurrogate(Char)

指示指定的 Char 对象是否是一个高代理项。Indicates whether the specified Char object is a high surrogate.

IsHighSurrogate(String, Int32)

指示字符串中指定位置处的 Char 对象是否为高代理项。Indicates whether the Char object at the specified position in a string is a high surrogate.

IsLetter(Char)

指示指定的 Unicode 字符是否属于 Unicode 字母类别。Indicates whether the specified Unicode character is categorized as a Unicode letter.

IsLetter(String, Int32)

指示指定字符串中位于指定位置处的指定字符串是否属于 Unicode 字母类别。Indicates whether the character at the specified position in a specified string is categorized as a Unicode letter.

IsLetterOrDigit(Char)

指示指定的 Unicode 字符是否属于字母或十进制数字类别。Indicates whether the specified Unicode character is categorized as a letter or a decimal digit.

IsLetterOrDigit(String, Int32)

指示指定字符串中位于指定位置处的字符是否属于字母或十进制数字类别。Indicates whether the character at the specified position in a specified string is categorized as a letter or a decimal digit.

IsLower(Char)

指示指定的 Unicode 字符是否属于小写字母类别。Indicates whether the specified Unicode character is categorized as a lowercase letter.

IsLower(String, Int32)

指示指定字符串中位于指定位置处的字符是否属于小写字母类别。Indicates whether the character at the specified position in a specified string is categorized as a lowercase letter.

IsLowSurrogate(Char)

指示指定的 Char 对象是否是一个低代理项。Indicates whether the specified Char object is a low surrogate.

IsLowSurrogate(String, Int32)

指示字符串中指定位置处的 Char 对象是否为低代理项。Indicates whether the Char object at the specified position in a string is a low surrogate.

IsNumber(Char)

指示指定的 Unicode 字符是否属于数字类别。Indicates whether the specified Unicode character is categorized as a number.

IsNumber(String, Int32)

指示指定字符串中位于指定位置的字符是否属于数字类别。Indicates whether the character at the specified position in a specified string is categorized as a number.

IsPunctuation(Char)

指示指定的 Unicode 字符是否属于标点符号类别。Indicates whether the specified Unicode character is categorized as a punctuation mark.

IsPunctuation(String, Int32)

指示指定字符串中位于指定位置处的字符是否属于标点符号类别。Indicates whether the character at the specified position in a specified string is categorized as a punctuation mark.

IsSeparator(Char)

指示指定的 Unicode 字符是否属于分隔符类别。Indicates whether the specified Unicode character is categorized as a separator character.

IsSeparator(String, Int32)

指示指定字符串中位于指定位置处的字符是否属于分隔符类别。Indicates whether the character at the specified position in a specified string is categorized as a separator character.

IsSurrogate(Char)

指示指定的字符是否具有指定的代理项代码单位。Indicates whether the specified character has a surrogate code unit.

IsSurrogate(String, Int32)

指示指定字符串中位于指定位置的字符是否具有代理项代码单位。Indicates whether the character at the specified position in a specified string has a surrogate code unit.

IsSurrogatePair(Char, Char)

指示两个指定的 Char 对象是否形成一个代理项对。Indicates whether the two specified Char objects form a surrogate pair.

IsSurrogatePair(String, Int32)

指示字符串中指定位置处的两个相邻 Char 对象是否形成一个代理项对。Indicates whether two adjacent Char objects at a specified position in a string form a surrogate pair.

IsSymbol(Char)

指示指定的 Unicode 字符是否属于符号字符类别。Indicates whether the specified Unicode character is categorized as a symbol character.

IsSymbol(String, Int32)

指示指定字符串中位于指定位置处的字符是否属于符号字符类别。Indicates whether the character at the specified position in a specified string is categorized as a symbol character.

IsUpper(Char)

指示指定的 Unicode 字符是否属于大写字母类别。Indicates whether the specified Unicode character is categorized as an uppercase letter.

IsUpper(String, Int32)

指示指定字符串中位于指定位置处的字符是否属于大写字母类别。Indicates whether the character at the specified position in a specified string is categorized as an uppercase letter.

IsWhiteSpace(Char)

指示指定的 Unicode 字符是否属于空格类别。Indicates whether the specified Unicode character is categorized as white space.

IsWhiteSpace(String, Int32)

指示指定字符串中位于指定位置处的字符是否属于空格类别。Indicates whether the character at the specified position in a specified string is categorized as white space.

Parse(String)

将指定字符串的值转换为它的等效 Unicode 字符。Converts the value of the specified string to its equivalent Unicode character.

ToLower(Char)

将 Unicode 字符的值转换为它的小写等效项。Converts the value of a Unicode character to its lowercase equivalent.

ToLower(Char, CultureInfo)

使用指定的区域性特定格式设置信息将指定 Unicode 字符的值转换为它的小写等效项。Converts the value of a specified Unicode character to its lowercase equivalent using specified culture-specific formatting information.

ToLowerInvariant(Char)

使用固定区域性的大小写规则,将 Unicode 字符的值转换为其小写等效项。Converts the value of a Unicode character to its lowercase equivalent using the casing rules of the invariant culture.

ToString()

将此实例的值转换为其等效的字符串表示形式。Converts the value of this instance to its equivalent string representation.

ToString(Char)

将指定的 Unicode 字符转换为它的等效字符串表示形式。Converts the specified Unicode character to its equivalent string representation.

ToString(IFormatProvider)

使用指定的区域性特定格式信息将此实例的值转换为它的等效字符串表示形式。Converts the value of this instance to its equivalent string representation using the specified culture-specific format information.

ToUpper(Char)

将 Unicode 字符的值转换为它的大写等效项。Converts the value of a Unicode character to its uppercase equivalent.

ToUpper(Char, CultureInfo)

使用指定的区域性特定格式设置信息将指定 Unicode 字符的值转换为它的大写等效项。Converts the value of a specified Unicode character to its uppercase equivalent using specified culture-specific formatting information.

ToUpperInvariant(Char)

使用固定区域性的大小写规则,将 Unicode 字符的值转换为其大写等效项。Converts the value of a Unicode character to its uppercase equivalent using the casing rules of the invariant culture.

TryParse(String, Char)

将指定字符串的值转换为它的等效 Unicode 字符。Converts the value of the specified string to its equivalent Unicode character. 一个指示转换是成功还是失败的返回代码。A return code indicates whether the conversion succeeded or failed.

显式接口实现

IComparable.CompareTo(Object)

将当前实例与同一类型的另一个对象进行比较,并返回一个整数,该整数指示当前实例在排序顺序中的位置是位于另一个对象之前、之后还是与其位置相同。Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.

IConvertible.GetTypeCode()

返回此实例的 TypeCodeReturns the TypeCode for this instance.

IConvertible.ToBoolean(IFormatProvider)

注意不支持此转换。Note This conversion is not supported. 尝试这样做会引发 InvalidCastExceptionAttempting to do so throws an InvalidCastException.

IConvertible.ToByte(IFormatProvider)

有关此成员的说明,请参见 ToByte(IFormatProvider)For a description of this member, see ToByte(IFormatProvider).

IConvertible.ToChar(IFormatProvider)

有关此成员的说明,请参见 ToChar(IFormatProvider)For a description of this member, see ToChar(IFormatProvider).

IConvertible.ToDateTime(IFormatProvider)

注意不支持此转换。Note This conversion is not supported. 尝试这样做会引发 InvalidCastExceptionAttempting to do so throws an InvalidCastException.

IConvertible.ToDecimal(IFormatProvider)

注意不支持此转换。Note This conversion is not supported. 尝试这样做会引发 InvalidCastExceptionAttempting to do so throws an InvalidCastException.

IConvertible.ToDouble(IFormatProvider)

注意不支持此转换。Note This conversion is not supported. 尝试这样做会引发 InvalidCastExceptionAttempting to do so throws an InvalidCastException.

IConvertible.ToInt16(IFormatProvider)

有关此成员的说明,请参见 ToInt16(IFormatProvider)For a description of this member, see ToInt16(IFormatProvider).

IConvertible.ToInt32(IFormatProvider)

有关此成员的说明,请参见 ToInt32(IFormatProvider)For a description of this member, see ToInt32(IFormatProvider).

IConvertible.ToInt64(IFormatProvider)

有关此成员的说明,请参见 ToInt64(IFormatProvider)For a description of this member, see ToInt64(IFormatProvider).

IConvertible.ToSByte(IFormatProvider)

有关此成员的说明,请参见 ToSByte(IFormatProvider)For a description of this member, see ToSByte(IFormatProvider).

IConvertible.ToSingle(IFormatProvider)

注意不支持此转换。Note This conversion is not supported. 尝试这样做会引发 InvalidCastExceptionAttempting to do so throws an InvalidCastException.

IConvertible.ToString(IFormatProvider)

使用指定的区域性特定格式设置信息将此实例的值转换为等效的字符串。Converts the value of this instance to an equivalent string, using the specified culture-specific formatting information.

IConvertible.ToType(Type, IFormatProvider)

有关此成员的说明,请参见 ToType(Type, IFormatProvider)For a description of this member, see ToType(Type, IFormatProvider).

IConvertible.ToUInt16(IFormatProvider)

有关此成员的说明,请参见 ToUInt16(IFormatProvider)For a description of this member, see ToUInt16(IFormatProvider).

IConvertible.ToUInt32(IFormatProvider)

有关此成员的说明,请参见 ToUInt32(IFormatProvider)For a description of this member, see ToUInt32(IFormatProvider).

IConvertible.ToUInt64(IFormatProvider)

有关此成员的说明,请参见 ToUInt64(IFormatProvider)For a description of this member, see ToUInt64(IFormatProvider).

适用于

线程安全性

此类型的所有成员都是线程安全的。All members of this type are thread safe. 看似修改实例状态的成员实际上返回用新值初始化的新实例。Members that appear to modify instance state actually return a new instance initialized with the new value. 与任何其他类型一样,读取和写入包含此类型的实例的共享变量时,必须通过锁保护以保证线程安全。As with any other type, reading and writing to a shared variable that contains an instance of this type must be protected by a lock to guarantee thread safety.

另请参阅