The correct way of casting an int to an enum

Possible Duplicate:
Cast int to Enum in C#

I fetch a int value from the database and want to cast the value to an enum variable. In 99.9% of the cases, the int will match one of the values in the enum declaration

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

eOrderType orderType = (eOrderType) FetchIntFromDb();

In the edge case, the value will not match (whether it's corruption of data or someone manually going in and messing with the data).

I could use a switch statement and catch the default and fix the situation, but it feels wrong. There has to be a more elegant solution.

Any ideas?


You can do

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

or rather I would cache the GetValues() results in a static variable and use it over and over gain.


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

bool defined = Enum.IsDefined(typeof(eOrderType), orderType);
链接地址: http://www.djcxy.com/p/22520.html

上一篇: 将int值分配给自定义枚举属性

下一篇: 将int转换为枚举的正确方法