关于如何转换枚举以及如果解析的值超出范围会发生什么,还有一些其他问题,例如:
public enum SomeTypes
{
SomeType1 = 1,
SomeType2 = 2,
SomeType3 = 3
}
public class SomeClass
{
...
var inRange = (SomeTypes) 1;
var outOfRange = (SomeTypes) 5;
...
}
Run Code Online (Sandbox Code Playgroud)
超出范围不会产生任何错误。但是我发现如果您尝试使用超出范围的值序列化-反序列化枚举,您会遇到奇怪的错误。例如,我得到了类似的东西
“错误解析消息或超时”
这让我一直在寻找枚举超出范围之外的其他原因。
处理此问题的建议是通过Enum.IsDefined. 这似乎工作得很好,但是在msdn上有一个相当大胆的警告:
“不要使用 System.Enum.IsDefined(System.Type,System.Object) 进行枚举范围检查,因为它基于枚举的运行时类型,该类型可能会因版本而异。”
所以,我的问题是,我们可以安全地使用Enum.IsDefined或检查枚举的值是否超出范围而不使用Enum.IsDefined?
使用Enum.GetValues():
public bool IsInRange(int value){
var values = Enum.GetValues(typeof(SomeTypes)).Cast<int>().OrderBy(x => x);
return value >= values.First() && value <= values.Last();
}
Run Code Online (Sandbox Code Playgroud)
[编辑]
如果您想检查该项目是否已定义,而不仅仅是检查它是否在范围内,您可以执行类似的操作:
public bool IsDefined(int value){
var values = Enum.GetValues(typeof(SomeTypes)).Cast<int>().OrderBy(x => x);
return values.Contains(value);
}
Run Code Online (Sandbox Code Playgroud)
有一个更简单的选择:
int value;
bool isInRange = !string.IsNullOrEmpty(Enum.GetName(typeof(myEnumType), value));
Run Code Online (Sandbox Code Playgroud)
我对对象做了类似的事情DataContract
你必须用它来装饰列表中的项目[EnumMember],然后你可以用这个方法获取枚举名称。所以你会知道枚举中是否存在值,因为返回他的枚举名称。
public static string GetEnumNameFromValue(System.Type typeEnum, string value)
{
FieldInfo[] fis = typeEnum.GetFields();
foreach (FieldInfo fi in fis)
{
EnumMemberAttribute[] attributes = (EnumMemberAttribute[])fi.GetCustomAttributes(typeof(EnumMemberAttribute), false);
if (attributes.Length > 0)
{
if (string.Compare(attributes[0].Value, value, true) == 0)
{
return fi.Name;
}
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)