當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C# Boolean.Equals(Boolean)用法及代碼示例

此方法用於返回一個值,該值指示此實例是否等於指定的布爾對象。

用法:

public bool Equals (bool obj);

在這裏,obj是一個布爾值,用於與此實例進行比較。


返回值:如果obj與該實例具有相同的值,則此方法返回true,否則返回false。

以下示例程序旨在說明Boolean.Equals(bool obj)方法的用法:

示例1:

// C# program to demonstrate 
// Boolean.Parse(String) 
// Method 
using System; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
  
        // passing different values 
        // to the method to check 
        check(true, true); 
        check(true, false); 
        check(false, true); 
        check(false, false); 
    } 
  
    // Defining check method 
    public static void check(bool input1, bool input2) 
    { 
  
        // declaring bool variable 
        bool val; 
  
        // getting parsed value 
        val = input1.Equals(input2); 
  
        // cheking the equivalency 
        if (val == true) 
            Console.WriteLine("{0} is equal to {1}", 
                                    input1, input2); 
  
        else
            Console.WriteLine("{0} is not equal to {1}", 
                                        input1, input2); 
    } 
}
輸出:
True is equal to True
True is not equal to False
False is not equal to True
False is equal to False

示例2:

// C# program to demonstrate 
// Boolean.Parse(String) 
// Method 
using System; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
  
        // Declaring the variable  
        // input1 and input2 
        bool input1, input2; 
  
        // initializing the variables 
        input1 = true; 
        input2 = false; 
  
        // cheking the equality 
        bool val = input1.Equals(input2); 
  
        // cheking the equivalency 
        if (val == true) 
            Console.WriteLine("input1 is equal to input2"); 
  
        else
            Console.WriteLine("input1 is not equal to input2"); 
    } 
}
輸出:
input1 is not equal to input2

注意:此方法實現了System.IEquatable<T>接口,並且比Equals稍好一些,因為它不必將obj參數轉換為對象。

參考:



相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 C# | Boolean.Equals(Boolean) Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。