C# 列舉 Equals 方法


使用 Equals() 方法找出列舉之間的相等性。

假設我們有以下列舉。

enum Products { HardDrive, PenDrive, Keyboard};

建立兩個 Product 物件並分配相同的值。

Products prod1 = Products.HardDrive;
Products prod2 = Products.HardDrive;

現在使用 Equals() 方法檢查相等性。結果為 True,因為兩者有著相同的底層值。

示例

 現場演示

using System;
class Program {
   enum Products {HardDrive, PenDrive, Keyboard};
   enum ProductsNew { Mouse, HeadPhone, Speakers};
   static void Main() {
      Products prod1 = Products.HardDrive;
      Products prod2 = Products.HardDrive;
      ProductsNew newProd1 = ProductsNew.HeadPhone;
      ProductsNew newProd2 = ProductsNew.Speakers;
      Console.WriteLine("Both are same products = {0}", prod1.Equals(prod2) ? "Yes" : "No");
      Console.WriteLine("Both are same products = {0}", newProd1.Equals(newProd2) ? "Yes" : "No");
   }
}

輸出

Both are same products = Yes
Both are same products = No

更新於:23-Jun-2020

628 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.