Computer >> Máy Tính >  >> Lập trình >> C#

Phương pháp bình đẳng trong C # Enum

Để tìm bằng nhau giữa các enum, hãy sử dụng phương thức Equals ().

Giả sử chúng ta có Enum sau.

enum Products { HardDrive, PenDrive, Keyboard};

Tạo hai đối tượng Sản phẩm và gán các giá trị giống nhau.

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

Bây giờ hãy kiểm tra sự bằng nhau bằng cách sử dụng phương thức Equals (). Nó sẽ là True vì cả hai đều có cùng giá trị cơ bản.

Ví dụ

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

Đầu ra

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