📜  如何在C#中比较Enum值?

📅  最后修改于: 2021-05-29 18:30:19             🧑  作者: Mango

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)); 
      
          
    } 
} 

运行时错误:

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.enum.compareto?view=netframework-4.8