说我有以下声明:
public enum Complexity { Low = 0, Normal = 1, Medium = 2, High = 3 }
public enum Priority { Normal = 1, Medium = 2, High = 3, Urgent = 4 }
Run Code Online (Sandbox Code Playgroud)
我想编码它,以便我可以得到枚举值(不是索引,就像我之前提到的那样):
//should store the value of the Complexity enum member Normal, which is 1
int complexityValueToStore = EnumHelper.GetEnumMemberValue(Complexity.Normal);
//should store the value 4
int priorityValueToStore = EnumHelper.GetEnumMemberValue(Priority.Urgent);
Run Code Online (Sandbox Code Playgroud)
这个可重用的函数应该怎么样?
TIA!-ren
Jon*_*eet 15
修改后的答案(问题澄清后)
不,没有什么比演员更干净了.它比方法调用,更便宜,更短等更具信息性.它的影响力与你可能希望的一样低.
请注意,如果您想编写一个通用方法来进行转换,您还必须指定将其转换为的内容:枚举可以基于byte或long例如.通过投入演员,你明确地说出你要将它转换成什么,它就是这样做的.
原始答案
"指数"究竟是什么意思?你的意思是数值吗?刚刚施展int.如果你的意思是"在枚举中的位置",你必须确保这些值是按数字顺序排列的(因为它是Enum.GetValues给出的 - 而不是声明顺序),然后执行:
public static int GetEnumMemberIndex<T>(T element)
where T : struct
{
T[] values = (T[]) Enum.GetValues(typeof(T));
return Array.IndexOf(values, element);
}
Run Code Online (Sandbox Code Playgroud)
您可以通过强制转换找到枚举的整数值:
int complexityValueToStore = (int)Complexity.Normal;
Run Code Online (Sandbox Code Playgroud)