The correct way of casting an int to an enum [duplicate]
Possible Duplicate:
Cast int to E开发者_运维知识库num 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 use the IsDefined
method to check if a value is among the defined values:
bool defined = Enum.IsDefined(typeof(eOrderType), orderType);
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.
精彩评论