type casting classes mimiking enums
我使用第三方应用程序进行输出。有几个int属性,我想通过枚举处理不同属性的int值。
属性1可以是0,1,2属性2可以是0,1属性3可以是1,2
我认为我应该有枚举继承,这在C中不是选项。
所以我用类解决了这个问题(我用的是TonoNam的另一个主题的答案:https://stackoverflow.com/a/23430174/4273304)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | public class MyEnum : IEquatable<MyEnum> { public static readonly MyEnum Undefined = new MyEnum(-1,"Undefined"); public int Value { get; private set; } public string Name { get; private set; } protected MyEnum(int value, string name) { this.Value = value; this.Name = name; } public bool Equals(MyEnum b) { return this.Name == b.Name && this.Value == b.Value; } public override string ToString() { return this.Name; } public static T Parse<T>(int value) { object obj; Type t_type = typeof(T); var fiList = t_type.GetFields(BindingFlags.Public | BindingFlags.Static).Where(f => f.FieldType == typeof(T)).ToArray(); foreach(FieldInfo en in fiList) { object tmp = en.GetValue(null); if (((MyEnum)tmp).Value == value) return (T)tmp; } obj = MyEnum.Undefined; return (T)obj; } } public class MyEnumChild1 : MyEnum { public static readonly MyEnumChild1 A = new MyEnumChild1(0,"A"); public static readonly MyEnumChild1 B = new MyEnumChild1(1,"B"); private MyEnumChild1(int value, string name) : base(value, name) { } } public class MyEnumChild2 : MyEnum { public static readonly MyEnumChild2 A = new MyEnumChild2(0,"A"); public static readonly MyEnumChild2 C = new MyEnumChild2(1,"C"); private MyEnumChild2(int value, string name) : base(value, name) { } } public class MyEnumChild3 : MyEnum { public static readonly MyEnumChild3 D = new MyEnumChild3(0,"D"); public static readonly MyEnumChild3 E = new MyEnumChild3(1,"E"); private MyEnumChild3(int value, string name) : base(value, name) { } } |
这个解决方案符合我的目的,但我不知道如何将int转换为myEnumChild1。我创建了一个解析器方法:
1 | MyEnumChild1 MEC1 = MyEnum.Parse <MyEnumChild1>(1); |
它似乎工作得很好,mec1现在是myeumchild1.b,但我不确定。
您认为我的解析器方法有多安全?此代码中是否有任何错误,或者我可以安全地使用它吗?
你知道更好、优雅或更简单的石膏解决方案吗?
首先,您的
1 | public static T Parse<T>(int value) where T : MyEnum |
其次,您可以使其受保护,并以这种方式在每个派生枚举中实现一个强制转换运算符:
1 2 3 4 | public static explicit operator MyEnumChild1(int value) { return Parse<MyEnumChild1>(value); } |
以更经典的方式使用它:
1 | MyEnumChild1 mec1 = (MyEnumChild1)1 |