问题描述
说我有以下声明: public enum Complexity {Low = 0,Normal = 1,Medium = High = 3}
public enum Priority {Normal = 1,Medium = 2,High = 3,Urgent = 4}
,我想编写它,以便我可以获得枚举值(不像前面提到的索引):
//应该存储复杂性枚举成员Normal的值,这是1
int complexityValueToStore = EnumHelper.GetEnumMemberValue(Complexity.Normal);
//应存储值4
int priorityValueToStore = EnumHelper.GetEnumMemberValue(Priority.Urgent);
这个可重用的功能应该怎么样?
TIA!
-ren
修改后的答案(问题澄清后)
不,没有比演员更干净。它比方法调用更便利,更便宜,更短等。它的影响力与您可能希望的影响相当。
请注意,如果您想编写通用方法要进行转换,您必须指定要将其转换为以下内容:枚举可以基于字节
或 long
例如。通过放入演员,你明确地说出你想要转换的东西,它只是这样做。
原始答案
index是什么意思?你的意思是数值吗?只是转换为 int
。如果你的意思是在枚举中的位置,你必须确保这些值是按照数字顺序排列的(因为这是 Enum.GetValues
给出的,而不是声明顺序)然后做:
public static int GetEnumMemberIndex&T;(T元素)
其中T:struct
{
T [] values =(T [])Enum.GetValues(typeof(T));
return Array.IndexOf(values,element);
}
say I have the following declarations:
public enum Complexity { Low = 0, Normal = 1, Medium = 2, High = 3 }
public enum Priority { Normal = 1, Medium = 2, High = 3, Urgent = 4 }
and I want to code it so that I could get the enum value (not the index, like I earlier mentioned):
//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);
How should this reusable function look like?
tia!-ren
Revised answer (after question clarification)
No, there's nothing cleaner than a cast. It's more informative than a method call, cheaper, shorter etc. It's about as low impact as you could possibly hope for.
Note that if you wanted to write a generic method to do the conversion, you'd have to specify what to convert it to as well: the enum could be based on byte
or long
for example. By putting in the cast, you explicitly say what you want to convert it to, and it just does it.
Original answer
What do you mean by "index" exactly? Do you mean the numeric value? Just cast to int
. If you mean "position within enum" you'd have to make sure the values are in numeric order (as that's what Enum.GetValues
gives - not the declaration order), and then do:
public static int GetEnumMemberIndex<T>(T element)
where T : struct
{
T[] values = (T[]) Enum.GetValues(typeof(T));
return Array.IndexOf(values, element);
}
这篇关于C#函数接受枚举项并返回枚举值(不是索引)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!