繁体   English   中英

C#函数接受枚举项并返回枚举值(不是索引)

[英]C# function that accepts an Enum item and returns the enum value (not the index)

说我有以下声明:

public enum Complexity { Low = 0, Normal = 1, Medium = 2,  High = 3 }
public enum Priority { Normal = 1, Medium = 2,  High = 3, Urgent = 4 }

我想编码它,以便我可以得到枚举值(不是索引,就像我之前提到的那样):

//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); 

这个可重用的函数应该怎么样?

TIA! -ren

修改后的答案(问题澄清后)

不,没有什么比演员更干净了。 它比方法调用,更便宜,更短等更具信息性。它的影响力与您可能希望的一样低。

请注意,如果您想编写一个通用方法来进行转换,您还必须指定将其转换为的内容:例如,枚举可以基于bytelong 通过投入演员,你明确地说出你要将它转换成什么,它就是这样做的。

原始答案

“指数”究竟是什么意思? 你的意思是数值吗? 刚刚转为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);
}

您可以通过强制转换找到枚举的整数值:

int complexityValueToStore = (int)Complexity.Normal;

我所知道的最通用的方法是使用反射读取value__字段。 这种方法不会对枚举的基础类型做出任何假设,因此它将适用于不基于Int32枚举。

public static object GetValue(Enum e)
{
    return e.GetType().GetField("value__").GetValue(e);
}

Debug.Assert(Equals(GetValue(DayOfWeek.Wednesday), 3));                //Int32
Debug.Assert(Equals(GetValue(AceFlags.InheritOnly), (byte) 8));        //Byte
Debug.Assert(Equals(GetValue(IOControlCode.ReceiveAll), 2550136833L)); //Int64

注意:我只使用Microsoft C#编译器对此进行了测试。 遗憾的是,这似乎没有内置的方式。

我意识到这不是你问的问题,但是你可能会欣赏它。

我发现如果你知道枚举的最小值是什么,你可以找到没有强制转换的枚举的整数值:

public enum Complexity { Low = 0, Normal = 1, Medium = 2,  High = 3 }

int valueOfHigh = Complexity.High - Complexity.Low;

除非您添加了一些最小值0或添加了1,否则这不适用于Priority:

public enum Priority { Normal = 1, Medium = 2,  High = 3, Urgent = 4 }

int valueOfUrgent = Priority.Urgent - Priority.Normal + 1;

我发现这种技术比铸造到int更具美学吸引力。

我不确定如果你有一个基于字节或长的枚举会发生什么 - 我怀疑你会得到字节或长差值。

这是解决问题的最简单方法:

public static void GetEnumMemberValue<T>(T enumItem) where T : struct 
{
    return (int) Enum.Parse(typeof(T), enumItem.ToString());
}

这个对我有用。

如果你想要这个值,你可以将枚举转换为int。 这将设置complexityValueToStore == 1和priorityValueToStore == 4。

如果你想获得索引(即:Priority.Urgent == 3),你可以使用Enum.GetValues ,然后在该列表中找到当前枚举的索引。 但是,返回列表中枚举的顺序可能与您的代码中的顺序不同。

然而,第二种选择首先打败了Enum的目的 - 你试图拥有离散值而不是列表和索引。 如果那就是你想要的,我会重新考虑你的需求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM