如果我有以下枚举:
public enum ReturnValue{ Success = 0, FailReason1 = 1, FailReason2 = 2 //Etc... }
我回来时可以避免施放,像这样:
public static int main(string[] args){ return (int)ReturnValue.Success; }
如果不是,为什么默认情况下不将枚举值视为int?
枚举应该是类型安全的.我认为他们并没有让他们暗中倾倒以阻止其他用途.虽然框架允许您为它们分配常量值,但您应该重新考虑您的意图.如果您主要使用枚举来存储常量值,请考虑使用静态类:
public static class ReturnValue { public const int Success = 0; public const int FailReason1 = 1; public const int FailReason2 = 2; //Etc... }
这可以让你这样做.
public static int main(string[] args){ return ReturnValue.Success; }
编辑
当你不希望提供值枚举是当你想将它们结合起来.见下面的例子:
[Flags] // indicates bitwise operations occur on this enum public enum DaysOfWeek : byte // byte type to limit size { Sunday = 1, Monday = 2, Tuesday = 4, Wednesday = 8, Thursday = 16, Friday = 32, Saturday = 64, Weekend = Sunday | Saturday, Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday }
然后可以通过使用按位数学来消耗此枚举.有些应用程序请参见下面的示例.
public static class DaysOfWeekEvaluator { public static bool IsWeekends(DaysOfWeek days) { return (days & DaysOfWeek.Weekend) == DaysOfWeek.Weekend; } public static bool IsAllWeekdays(DaysOfWeek days) { return (days & DaysOfWeek.Weekdays) == DaysOfWeek.Weekdays; } public static bool HasWeekdays(DaysOfWeek days) { return ((int) (days & DaysOfWeek.Weekdays)) > 0; } public static bool HasWeekendDays(DaysOfWeek days) { return ((int) (days & DaysOfWeek.Weekend)) > 0; } }