- 枚举是值类型,不可以定义字段属性方法等。
- 枚举和字符串相互转化:
-
public enum ReportType { Day, Week, Month, Quarter, Year } private static void TestEnum() { ReportType day = ReportType.Day; string daystr = "Day"; int dayInt = 0; //1.枚举转字符串 var enum_to_str = day.ToString(); var enum_to_str2 = Enum.GetName(typeof(ReportType), ReportType.Day);//效率高 //2.枚举转值 int enum_to_int = day.GetHashCode(); int enum_to_int2 = (int)day; int enum_to_int3 = Convert.ToInt32(day); //3.字符串转枚举 ReportType day_temp = (ReportType)Enum.Parse(typeof(ReportType), daystr); //4.枚举字符串转值 int day_int = (int)(ReportType)Enum.Parse(typeof(ReportType), daystr); //5.值转枚举 ReportType int_to_enum = (ReportType)dayInt; ReportType int_to_enum2 = (ReportType)Enum.ToObject(typeof(ReportType), dayInt); //6.值转字符串 string int_to_str = Enum.GetName(typeof(ReportType), dayInt); ReportType reporttype= ReportType.Month; /******注意点*****/ string obj="155"; if (Enum.TryParse(obj, out reporttype))//obj 是数字时候未定义枚举时候的转化是成功的,必须走67行的判定 { if (Enum.IsDefined(typeof(ReportType), reporttype))//IsDefined内部用了反射 { Console.WriteLine(reporttype.ToString()); } else { Console.WriteLine("非枚举成员"); } } /******注意点*****/ }
4.其他的不多做介绍,注重实战