将int转换为枚举的正确方法

时间:2011-03-07 19:19:35

标签: c# enums

  

可能重复:
  Cast int to Enum in C#

我从数据库中获取一个int值,并希望将值转换为枚举变量。在99.9%的情况下,int将匹配枚举声明中的一个值

public enum eOrderType {
    Submitted = 1,
    Ordered = 2,
    InReview = 3,
    Sold = 4,
    ...
}

eOrderType orderType = (eOrderType) FetchIntFromDb();

在边缘情况下,该值将不匹配(无论是数据损坏还是手动进入并弄乱数据)。

我可以使用switch语句捕获default并修复情况,但感觉不对。必须有一个更优雅的解决方案。

有什么想法吗?

2 个答案:

答案 0 :(得分:5)

您可以使用IsDefined方法检查值是否在定义的值中:

bool defined = Enum.IsDefined(typeof(eOrderType), orderType);

答案 1 :(得分:0)

你可以做到

int value = FetchIntFromDb();
bool ok = System.Enum.GetValues(typeof(eOrderType)).Cast<int>().Contains(value);

或者更确切地说,我会将GetValues()结果缓存在一个静态变量中,然后一次又一次地使用它。