Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将int强制转换为enum的正确方法_C#_Enums - Fatal编程技术网

C# 将int强制转换为enum的正确方法

C# 将int强制转换为enum的正确方法,c#,enums,C#,Enums,可能重复: 我从数据库中获取一个int值,并希望将该值强制转换为枚举变量。在99.9%的情况下,int将匹配enum声明中的一个值 public enum eOrderType { Submitted = 1, Ordered = 2, InReview = 3, Sold = 4, ... } eOrderType orderType = (eOrderType) FetchIntFromDb(); 在edge的情况下,该值将不匹配(无论是数据损坏

可能重复:

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

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

eOrderType orderType = (eOrderType) FetchIntFromDb();
在edge的情况下,该值将不匹配(无论是数据损坏还是有人手动进入并弄乱数据)

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

有什么想法吗?

你可以

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

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

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

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

你看到另一个了吗?关于使用枚举的一般性评论:确保始终包含默认的0值
public enum eOrderType{None=0,Submitted=1,…}
我认为这是一个与“将int转换为enum”问题稍有不同的问题。碰巧,这个问题的第二高投票率答案也是这个问题的好答案。这是我最初的答案(基本上),直到我意识到Enum类中已经有一个方法可以做到这一点……;)