首页 > 文章列表 > Check if Two enums Are Equal or Not in C#

Check if Two enums Are Equal or Not in C#

400 2023-08-19

Enums, short for enumerations, are a fundamental part of the C# programming language. They allow developers to define a type of variable that can have one of a few predefined constants. Understanding how to compare two enums for equality can be a vital tool in your C# programming toolbox. This article will guide you through the process, and by the end, you will be proficient in comparing two enum values in C#.

Understanding Enums in C#

Before we move forward, it's essential to grasp what enums are. Enums are value types in C# and are used to represent a collection of named constants, usually called enumerator lists.

这是一个枚举的简单示例 −

public enum Days {
   Sunday,
   Monday,
   Tuesday,
   Wednesday,
   Thursday,
   Friday,
   Saturday
}

In this example, Days is an enum, and Sunday, Monday, etc., are its members.

比较两个枚举

在C#中,检查两个枚举值是否相等非常简单。您只需使用 == 运算符即可。

Example

这是一个例子 −

using System;

public enum Days {
   Monday,
   Tuesday,
   Wednesday,
   Thursday,
   Friday,
   Saturday,
   Sunday
}

public class Program {
   public static void Main() {
      Days day1 = Days.Monday;
      Days day2 = Days.Monday;

      if (day1 == day2) {
         Console.WriteLine("The days are equal.");
      } else {
         Console.WriteLine("The days are not equal.");
      }
   }
}

在这段代码片段中,我们首先定义了两个类型为Days的变量day1和day2。然后我们使用==运算符来检查day1和day2是否相等。

输出

The days are equal.

Comparing Enums with Different Cases

C#是区分大小写的,这意味着Days.Monday和Days.monday会被认为是不同的。然而,你可能会遇到这样的情况,你想比较两个枚举值,它们的拼写相同但大小写不同。

You can do this by converting the enum values to strings and then comparing the strings using the String.Equals method with StringComparison.OrdinalIgnoreCase as a parameter.

Example

这是一个例子 −

using System;

public enum Days {
   Monday,
   Tuesday,
   Wednesday,
   Thursday,
   Friday,
   Saturday,
   Sunday
}

public class Program {
   public static void Main() {
      string day1 = Days.Monday.ToString();
      string day2 = "monday";

      if (String.Equals(day1, day2, StringComparison.OrdinalIgnoreCase)) {
         Console.WriteLine("The days are equal.");
      } else {
         Console.WriteLine("The days are not equal.");
      }
   }
}

In this example, we first convert the enum values to strings. We then use the String.Equals method with StringComparison.OrdinalIgnoreCase to compare the strings without considering their case.

输出

The days are equal.

结论

In C#, comparing two enum values is simple and straightforward. By using the == operator, or the String.Equals method for case-insensitive comparisons, you can easily check if two enum values are equal.