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


C# Byte.CompareTo(Byte)用法及代碼示例


此方法用於將此實例與指定的8位無符號整數進行比較,並返回其相對值的指示。

用法:

public int CompareTo (byte value);

在此,該值是要比較的8位無符號整數。


返回值:此方法返回一個帶符號的整數,該整數指示此實例和值的相對順序。

  • 小於零:此實例小於值。
  • 零:此實例等於值。
  • 大於零:此實例大於值。

以下示例程序旨在說明Byte.CompareTo(Byte)方法的用法:

示例1:

// C# program to demonstrate 
// Byte.CompareTo(byte) 
// Method 
using System; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
  
        // Declaring val1 and val2 
        byte val1, val2; 
  
        // intializing the val1,  
        // val2 and val3 
        val1 = 12; 
        val2 = 13; 
  
        // getting compared constant 
        // using CompareTo method 
        int i = val2.CompareTo(val1); 
  
        // checking the condition 
        if (i > 0) 
            Console.Write("val2 is greater than val1"); 
  
        else if (i < 0) 
            Console.Write("val2 is less than val1"); 
  
        else
            Console.Write("val1 is equal to val1"); 
    } 
}
輸出:
val2 is greater than val1

示例2:

// C# program to demonstrate 
// Byte.CompareTo(byte) 
// Method 
using System; 
  
class GFG { 
  
    // Main Method 
    public static void Main() 
    { 
  
        // checking the condition 
        // calling check() method 
        check((byte)10, (byte)20); 
        check((byte)30, (byte)20); 
        check((byte)10, (byte)10); 
        check((byte)5, (byte)7); 
        check((byte)40, (byte)50); 
        check((byte)1, (byte)2); 
    } 
  
    // Defining the check method 
    public static void check(byte v1, byte v2) 
    { 
  
        // getting compared constant 
        // using CompareTo() method 
        int i = v1.CompareTo(v2); 
  
        // checking the condition 
        if (i > 0) 
            Console.WriteLine(v1 + " is greater than " + v2); 
  
        else if (i < 0) 
            Console.WriteLine(v1 + " is less than " + v2); 
  
        else
            Console.WriteLine(v1 + " is equal to " + v2); 
    } 
}
輸出:
10 is less than 20
30 is greater than 20
10 is equal to 10
5 is less than 7
40 is less than 50
1 is less than 2

參考:



相關用法


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