📜  C#| Char.CompareTo()方法

📅  最后修改于: 2021-05-29 14:11:45             🧑  作者: Mango

在C#中, Char.CompareTo()System.Char struct方法,该方法用于比较指定对象或值类型的此实例,并检查给定实例是在排序顺序的前面,之后还是在相同位置出现作为指定的对象或值类型。通过将不同类型的参数传递给该方法,可以重载该方法。

  1. Char.CompareTo(Char)方法
  2. Char.CompareTo(Object)方法

Char.CompareTo(Char)方法

此方法用于将此实例与指定的Char对象进行比较,并检查此实例是否在与指定Char对象的排序顺序相同的位置之前,之后或出现。

句法:

public int CompareTo(Char ch);

范围:

返回类型:返回一个带符号的数字,该数字以相对于ch参数的排序顺序显示实例的位置。此方法的返回类型为System.Int32 。下表显示了返回值的不同情况:

Return value Description
Less than zero This instance precedes ch.
Zero This instance has the same position in the sort as in ch.
Greater than zero This instance follows ch.

例子:

// C# program to demonstrate the 
// Char.CompareTo(Char) Method
using System;
  
class CompareToSample {
      
    // Main Method
    public static void Main()
    {
        char ch1 = 'Z';
        char ch2 = 'g';
        char ch3 = 'A';
          
        // using Char.CompareTo(Char) Method
        // returns 0 as this instance has
        // same position in the sort as in ch1
        Console.WriteLine('Z'.CompareTo(ch1));
          
        // using Char.CompareTo(Char) Method
        // returns -13 as this instance 
        // precedes ch2
        Console.WriteLine('Z'.CompareTo(ch2));
          
        // using Char.CompareTo(Char) Method
        // returns 25 as this instance follows
        // ch3
        Console.WriteLine('Z'.CompareTo(ch3));
    }
}
输出:
0
-13
25

Char.CompareTo(Object)方法

此方法用于将实例与指定对象进行比较,并检查该实例在与指定对象的排序顺序相同的位置之前,之后或是否出现在同一位置。 Char的任何实例的值都被认为大于null。

句法:

public int CompareTo(object obj);

范围:

返回类型:返回一个带符号的数字,该数字以相对于obj参数的排序顺序显示实例的位置。此方法的返回类型为System.Int32 。下表显示了返回值的不同情况:

Return value Description
Less than zero This instance precedes obj.
Zero This instance has the same position in the sort as in obj.
Greater than zero This instance follows obj or obj is null.

异常:如果obj不是Char对象,则此方法将提供ArgumentException

例子:

// C# program to illustrate the
// Char.CompareTo(Object) Method
using System;
  
class GeeksforGeeks {
      
    // Main method
    public static void Main()
    {
          
        // declaration of data type
        char ch1 = 'G';
        char ch2 = 'a';
        char ch3 = 'B';
        int output;
          
        // compare ch1 with G, as they are
        // equal so output will be zero
        output = ch1.CompareTo('G');
        Console.WriteLine(output);
          
        // compare ch3 with ch2
        // output is -31 which means
        // ch3 is less than ch2 by -31
        output = ch3.CompareTo(ch2);
        Console.WriteLine(output);
          
        // comapre ch1 with ch3
        // output is 5 which means
        // ch1 is greater then ch3 by 5
        output = ch1.CompareTo(ch3);
        Console.WriteLine(output);
    }
}
输出:
0
-31
5

参考: https://docs.microsoft.com/zh-cn/dotnet/api/system.char.compareto?view=netframework-4.7.2