摘要:enum DaysOfWeek{Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday}class Program{static void Main{DaysOfWeek today = DaysOfW
在 C# 中,访问枚举类型的成员非常直观。可以通过以下几种方式访问和操作枚举类型的成员。
enum DaysOfWeek{Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday}class Program{static void Main{DaysOfWeek today = DaysOfWeek.Monday;Console.WriteLine(today); // 输出: Monday}}解释:直接通过 枚举类型.枚举成员 的形式访问。解释:通过显式类型转换,将枚举成员转换为对应的整数值。DaysOfWeek day = (DaysOfWeek)1;Console.WriteLine(day); // 输出: Tuesdayforeach (DaysOfWeek day in Enum.GetValues(typeof(DaysOfWeek))){Console.WriteLine(day);}解释:Enum.GetValues 方法返回枚举类型中所有成员的集合,可以用来遍历。解释:Enum.GetName 方法根据枚举的整数值返回对应的成员名称。bool isDefined = Enum.IsDefined(typeof(DaysOfWeek), "Monday");Console.WriteLine(isDefined); // 输出: True解释:可以用 Enum.IsDefined 检查某个值或名称是否在枚举中定义。DaysOfWeek today = DaysOfWeek.Monday;Console.WriteLine(today.ToString); // 输出: Monday解释:ToString 方法返回枚举成员的名称字符串。[Flags]enum FileAccess{None = 0,Read = 1,Write = 2,Execute = 4}class Program{static void Main{FileAccess access = FileAccess.Read | FileAccess.Write;Console.WriteLine(access); // 输出: Read, Write}}enum DaysOfWeek{Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday}static class EnumExtensions{public static bool IsWeekend(this DaysOfWeek day){return day == DaysOfWeek.Saturday || day == DaysOfWeek.Sunday;}}class Program{static void Main{DaysOfWeek today = DaysOfWeek.Saturday;Console.WriteLine(today.IsWeekend); // 输出: True}}在 C# 中,访问枚举类型的成员可以通过直接引用、整数值转换、Enum 类的辅助方法、按位操作符(适用于 [Flags] 枚举)等方式实现。合理使用这些方式可以提升代码的可读性和灵活性。
来源:面试八股文
免责声明:本站系转载,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与本站联系,我们将在第一时间删除内容!