C# 枚举 CompareTo 方法

csharpprogrammingserver side programming

使用 C# 中的 CompareTo() 方法比较两个枚举。

该方法返回以下任意值 −

  • 小于零:源值小于目标值
  • 零:源值等于目标值
  • 大于零:源值大于目标值

示例

using System;
class Program {
   enum Products { HardDrive = 0, PenDrive = 4, Keyboard = 8 };
   static void Main() {
      Products prod1 = Products.HardDrive;
      Products prod2 = Products.PenDrive;
      Products prod3 = Products.Keyboard;
      Console.WriteLine("Stock for {0} is more than {1}?", prod3, prod2);
      Console.WriteLine( "{0}{1}",prod3.CompareTo(prod2) > 0 ? "Yes" : "No", Environment.NewLine );
   }
}

输出

Stock for Keyboard is more than PenDrive?
Yes

相关文章