此方法用于将当前实例与指定对象进行比较,并返回其相对值的符号。无论值如何,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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。