Enum.CompareTo(Object)方法用于将当前实例与指定对象进行比较,并返回其相对值的指示。
句法:
public int CompareTo (object target);
在此,目标是要比较的对象,也可以为空。
返回值:此方法返回一个带符号的数字,该数字显示当前实例和目标的相对值,如下所示:
- 小于零:如果当前实例的值小于目标的值。
- 零:如果当前实例的值等于目标的值。
- 大于零:如果当前实例的值大于目标的值,或者目标为null 。
例外情况:
- ArgumentException :如果目标实例和当前实例不是同一类型。
- InvalidOperationException :如果实例的类型不是SByte,Int16,Int32,Int64,Byte,UInt16,UInt32或UInt64 。
- NullReferenceException :如果当前实例为null。
下面的程序说明了上述方法的用法:
范例1:
// C# program to demonstrate the
// Enum.CompareTo(Object) Method
using System;
public class GFG
{
enum Color
{
RED, GREEN, BLUE
};
// Driver method
public static void Main(String[] args)
{
Color c1 = Color.RED;
Color c2 = Color.GREEN;
Color c3 = Color.RED;
Color c4 = Color.BLUE;
Console.Write("Comparing {0} with {1} : ", c1, c2);
// CompareTo method
Console.WriteLine(c1.CompareTo(c2));
Console.Write("Comparing {0} with {1} : ", c1, c3);
// CompareTo method
Console.WriteLine(c1.CompareTo(c3));
Console.Write("Comparing {0} with {1} : ", c4, c2);
// CompareTo method
Console.WriteLine(c4.CompareTo(c2));
}
}
输出:
Comparing RED with GREEN : -1
Comparing RED with RED : 0
Comparing BLUE with GREEN : 1
范例2:
// C# program to demonstrate the
// Enum.CompareTo(Object) Method
using System;
public class GFG
{
enum Color{Red, Blue};
enum Seasons {Winter, Summer};
// Driver method
public static void Main(String[] args)
{
Color c1 = Color.Red;
Color c2 = Color.Blue;
Seasons s1 = Seasons.Winter;
Seasons s2 = Seasons.Summer;
Console.Write("Comparing {0} with {1} : ", c1, c2);
// CompareTo method
Console.WriteLine(c1.CompareTo(c2));
Console.Write("Comparing {0} with {1} : ", c1, s1);
// using CompareTo method
// it will give exception
// as target and the current
// instance are not the same
// types
Console.WriteLine(c1.CompareTo(s1));
}
}
运行时错误:
Unhandled Exception:
System.ArgumentException: Object must be the same type as the enum. The type passed in was ‘GFG+Seasons’; the enum type was ‘GFG+Color’.
at System.Enum.CompareTo (System.Object target) <0x7ff9d1544610 + 0x000da> in <0f8aeac9d63d4b8aa575761bb4e65b79>:0
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.enum.compareto?view=netframework-4.8