此方法用於將當前實例與指定對象進行比較,並返回其相對值的符號。無論值如何,Byte的任何實例都將被視為大於null。
用法:
public int CompareTo (object value);
在這裏,它需要一個對象進行比較,或者為null。
返回值:它返回一個帶符號的整數,指示當前實例和value參數的相對順序,如下所示:
- 小於零:如果當前實例
- 零:如果當前實例=值
- 大於零:如果Current Instance> value或value為null。
異常:如果value不是Byte,則拋出ArgumentException。
以下示例程序旨在說明Byte.CompareTo(Object)方法的用法
示例1:
// C# program to demonstrate the
// Byte.CompareTo(object) Method
using System;
class GFG {
// Main Method
public static void Main()
{
try {
// Declaring and initializing value1
byte value1 = 10;
// Declaring and initializing value2
// converting to byte using explicit
// type casting
object value2 = (byte)87;
// 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 Byte");
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
}
輸出:
10 is less than 87
示例2:對於ArgumentException
// C# program to demonstrate the
// Byte.CompareTo(object) Method
using System;
using System.Globalization;
class GFG {
// Main Method
public static void Main()
{
try {
// Declaring and initializing value1
byte value1 = 10;
// Declaring and initializing value2
object value2 = (long)569874514;
// 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 Byte");
Console.Write("Exception Thrown: ");
Console.Write("{0}", e.GetType(), e.Message);
}
}
}
輸出:
value2 must be Byte Exception Thrown: System.ArgumentException
參考:
相關用法
- C# DateTimeOffset.Add()用法及代碼示例
- C# String.Contains()用法及代碼示例
- C# Math.Sin()用法及代碼示例
- C# Math.Cos()用法及代碼示例
- C# Dictionary.Add()用法及代碼示例
- C# Math.Tan()用法及代碼示例
- C# Math.Abs()方法用法及代碼示例
- C# Math.Exp()用法及代碼示例
- C# Math.Abs()函數用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 C# | Byte.CompareTo(Object) Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。