比较 C# 中的枚举成员
若要比较枚举成员,请使用 Enum.CompareTo() 方法。
首先,设置学生的数值。
enum StudentRank { Tom = 3, Henry = 2, Amit = 1 };
现在使用 compareTo() 方法比较一个枚举值与另一个。
Console.WriteLine( "{0}{1}", student1.CompareTo(student2) > 0 ? "Yes" : "No", Environment.NewLine );
以下是 C# 中比较枚举成员的代码。
示例
using System; public class Demo { enum StudentRank { Tom = 3, Henry = 2, Amit = 1 }; public static void Main() { StudentRank student1 = StudentRank.Tom; StudentRank student2 = StudentRank.Henry; StudentRank student3 = StudentRank.Amit; Console.WriteLine("{0} has more rank than {1}?", student1, student2); Console.WriteLine( "{0}{1}", student1.CompareTo(student2) > 0 ? "Yes" : "No", Environment.NewLine ); } }
输出
Tom has more rank than Henry? Yes
广告