[英]Get Enum name based on the Enum value
我已声明以下枚举:
public enum AfpRecordId
{
BRG = 0xD3A8C6,
ERG = 0xD3A9C6
}
我想从值中检索枚举对象:
private AfpRecordId GetAfpRecordId(byte[] data)
{
...
}
调用示例:
byte[] tempData = new byte { 0xD3, 0xA8, 0xC6 };
AfpRecordId tempId = GetAfpRecordId(tempData);
//tempId should be equals to AfpRecordId.BRG
我也想使用linq或lambda,只要它们可以提供更好或相等的性能。
简单:
int
(手动,或通过创建四字节数组并使用BitConverter.ToInt32
) int
为AfpRecordId
ToString
(您的主题行建议获取名称,但您的方法签名仅涉及值) 例如:
private static AfpRecordId GetAfpRecordId(byte[] data)
{
// Alternatively, switch on data.Length and hard-code the conversion
// for lengths 1, 2, 3, 4 and throw an exception otherwise...
int value = 0;
foreach (byte b in data)
{
value = (value << 8) | b;
}
return (AfpRecordId) value;
}
您可以使用Enum.IsDefined
来检查给定数据是否实际上是有效 ID。
至于性能 - 在你寻找更快的东西之前,检查一些简单的东西是否能给你足够好的性能。
如果数组具有已知大小(我假设大小为3),您可以将元素添加到一起并将结果转换为枚举
private AfpRecordId GetAfpRecordId(byte[] tempData){
var temp = tempData[0] * 256*256 + tempData[1] * 256 +tempData[2];
return (AfpRecordId)temp;
}
另一种方法是使用移位运算符
private AfpRecordId GetAfpRecordId(byte[] tempData){
var temp = (int)tempData[0]<<16 + (int)tempData[1] * 8 +tempData[2];
return (AfpRecordId)temp;
}
假设tempData
有3个元素,则使用Enum.GetName (typeof (AfpRecordId), tempData[0] * 256*256 + tempData[1] * 256 +tempData[2])
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.