C# 枚举 Equals 方法

csharpprogrammingserver side programming

要查找枚举之间的相等性,请使用 Equals() 方法。

假设我们有以下枚举。

enum Products { HardDrive, PenDrive, Keyboard};

创建两个 Products 对象并分配相同的值。

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

相关文章