可能重复:
在C#中将int强制转换为枚举
我从数据库中获取一个int值,并希望将值转换为枚举变量.在99.9%的情况下,int将匹配枚举声明中的一个值
public enum eOrderType {
Submitted = 1,
Ordered = 2,
InReview = 3,
Sold = 4,
...
}
eOrderType orderType = (eOrderType) FetchIntFromDb();
Run Code Online (Sandbox Code Playgroud)
在边缘情况下,该值将不匹配(无论是数据损坏还是某人手动进入并弄乱数据).
我可以使用switch语句捕获default并修复情况,但感觉不对.必须有一个更优雅的解决方案.
有任何想法吗?
您可以使用该IsDefined方法检查值是否在定义的值中:
bool defined = Enum.IsDefined(typeof(eOrderType), orderType);
Run Code Online (Sandbox Code Playgroud)
你可以做
int value = FetchIntFromDb();
bool ok = System.Enum.GetValues(typeof(eOrderType)).Cast<int>().Contains(value);
Run Code Online (Sandbox Code Playgroud)
或者更确切地说,我会将 GetValues() 结果缓存在静态变量中,并一遍又一遍地使用它。