C# 列舉 CompareTo 方法


使用 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

更新於: 2020 年 6 月 23 日

340 次瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.