如何在C#中将int转换为枚举?
当前回答
对于数值,这是更安全的,因为无论发生什么情况,它都会返回一个对象:
public static class EnumEx
{
static public bool TryConvert<T>(int value, out T result)
{
result = default(T);
bool success = Enum.IsDefined(typeof(T), value);
if (success)
{
result = (T)Enum.ToObject(typeof(T), value);
}
return success;
}
}
其他回答
如果您已经准备好使用4.0.NETFramework,那么有一个新的Enum.TryParse()函数非常有用,并且可以很好地使用[Flags]属性。请参阅Enum.TryParse方法(字符串,TEnum%)
对于字符串,可以执行以下操作:
var result = Enum.TryParse(typeof(MyEnum), yourString, out yourEnum)
并确保检查结果以确定转换是否失败。
对于int,可以执行以下操作:
MyEnum someValue = (MyEnum)myIntValue;
对于数值,这是更安全的,因为无论发生什么情况,它都会返回一个对象:
public static class EnumEx
{
static public bool TryConvert<T>(int value, out T result)
{
result = default(T);
bool success = Enum.IsDefined(typeof(T), value);
if (success)
{
result = (T)Enum.ToObject(typeof(T), value);
}
return success;
}
}
我需要两个指示:
YourEnum possibleEnum = (YourEnum)value; // There isn't any guarantee that it is part of the enum
if (Enum.IsDefined(typeof(YourEnum), possibleEnum))
{
// Value exists in YourEnum
}
它可以帮助您将任何输入数据转换为用户所需的枚举。假设您有一个类似下面的枚举,默认为int。请在枚举的第一个添加默认值。当与输入值不匹配时,在helpers方法中使用。
public enum FriendType
{
Default,
Audio,
Video,
Image
}
public static class EnumHelper<T>
{
public static T ConvertToEnum(dynamic value)
{
var result = default(T);
var tempType = 0;
//see Note below
if (value != null &&
int.TryParse(value.ToString(), out tempType) &&
Enum.IsDefined(typeof(T), tempType))
{
result = (T)Enum.ToObject(typeof(T), tempType);
}
return result;
}
}
注意:这里我尝试将值解析为int,因为enum默认为int如果像这样定义枚举,则为字节类型。
public enum MediaType : byte
{
Default,
Audio,
Video,
Image
}
您需要将helper方法的解析从
int.TryParse(value.ToString(), out tempType)
to
byte.TryParse(value.ToString(),out tempType)
我检查我的方法是否有以下输入
EnumHelper<FriendType>.ConvertToEnum(null);
EnumHelper<FriendType>.ConvertToEnum("");
EnumHelper<FriendType>.ConvertToEnum("-1");
EnumHelper<FriendType>.ConvertToEnum("6");
EnumHelper<FriendType>.ConvertToEnum("");
EnumHelper<FriendType>.ConvertToEnum("2");
EnumHelper<FriendType>.ConvertToEnum(-1);
EnumHelper<FriendType>.ConvertToEnum(0);
EnumHelper<FriendType>.ConvertToEnum(1);
EnumHelper<FriendType>.ConvertToEnum(9);
对不起我的英语
推荐文章
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- VS2013外部构建错误"error MSB4019: The imported project <path> was not found"
- 从另一个列表id中排序一个列表
- 等待一个无效的异步方法
- 无法加载文件或程序集…参数不正确
- c#中枚举中的方法
- 如何从字符串中删除新的行字符?
- 如何设置一个默认值与Html.TextBoxFor?
- 检查属性是否有属性
- 格式化XML字符串以打印友好的XML字符串
- 返回内容与IHttpActionResult非ok响应
- 从IEnumerable<KeyValuePair<>>重新创建字典
- c#测试用户是否有对文件夹的写权限