📜  C#| Boolean.CompareTo(Object)方法

📅  最后修改于: 2021-05-29 19:24:53             🧑  作者: Mango

Boolean.CompareTo(Object)方法用于将当前实例与指定对象进行比较,并返回一个整数,该整数表明它们之间的关系。

句法:

public int CompareTo (object obj);

在这里,需要一个对象与当前实例进行比较或为null。

返回值:该方法返回一个带符号的整数,该整数显示当前实例和obj的相对顺序。

  • 小于零:如果此实例为false且obj为true
  • 零:如果此实例和obj相等(都为true或均为false )。
  • 大于零:如果此实例为true,而obj为falsenull

异常:如果obj不是布尔值,则抛出ArgumentException。

范例1:

// C# program to demonstrate the
// Boolean.CompareTo(Object) Method
using System;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // Declaring and initializing value1
            bool value1 = true;
  
            // Declaring and initializing value2
            object value2 = true;
  
            // using CompareTo() method
            int status = value1.CompareTo(value2);
  
            // checking the status
            if (status > 0)
                Console.WriteLine("{0} is greater than {1}",
                                            value1, value2);
  
            else if (status < 0)
                Console.WriteLine("{0} is less than {1}",
                                         value1, value2);
            else
                Console.WriteLine("{0} is equal to {1}",
                                        value1, value2);
        }
  
        catch (ArgumentException e) 
        {
            Console.WriteLine("value2 must be Boolean");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
True is equal to True

示例2:对于ArgumentException

// C# program to demonstrate the
// Boolean.CompareTo(Object) Method
using System;
using System.Globalization;
  
class GFG {
  
    // Main Method
    public static void Main()
    {
        try {
  
            // Declaring and initializing value1
            bool value1 = true;
  
            // Declaring and initializing value2
            object value2 = 53554;
  
            // using CompareTo() method
            int status = value1.CompareTo(value2);
  
            // checking the status
            if (status > 0)
                Console.WriteLine("{0} is greater than {1}",
                                            value1, value2);
  
            else if (status < 0)
                Console.WriteLine("{0} is less than {1}",
                                         value1, value2);
            else
                Console.WriteLine("{0} is equal to {1}",
                                        value1, value2);
        }
  
        catch (ArgumentException e) 
        {
            Console.WriteLine("value2 must be Boolean");
            Console.Write("Exception Thrown: ");
            Console.Write("{0}", e.GetType(), e.Message);
        }
    }
}
输出:
value2 must be Boolean
Exception Thrown: System.ArgumentException

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.boolean.compareto?view=netframework-4.8#System_Boolean_CompareTo_System_Object_