示例代码
public enum TypeEnum
{
[Text("进行中")]
Doing = 1,
[Text("完成")]
Done = 2,
[Text("已被删除")]
Deleted = 9,
}
public class TextAttribute : Attribute
{
public TextAttribute(string value)
{
Value = value;
}
public string Value { get; set; }
}
public static class Utils
{
public static T ToEnum<T>(this int value) where T : struct, Enum
{
if (Enum.TryParse(value.ToString(), out T e) == false || Enum.IsDefined(typeof(T), e) == false)
throw new Exception(value + " 转换失败");
return e;
}
public static T ToEnum<T>(this string value) where T : struct, Enum
{
if (Enum.TryParse(value, out T e) == false || Enum.IsDefined(typeof(T), e) == false)
throw new Exception(value + " 转换失败");
return e;
}
}
测试代码
static void Test06()
{
TypeEnum typeEnum = TypeEnum.Doing;
int v1 = (int)typeEnum;
string v2 = typeEnum.ToString();
string v3 = string.Empty;
var enumType = typeEnum.GetType();
{
var fieldInfo = enumType.GetField(typeEnum.ToString());
var attrs = fieldInfo.GetCustomAttributes(typeof(TextAttribute), false);
if (attrs.Length == 1)
{
v3 = ((TextAttribute)attrs[0]).Value;
}
}
Console.WriteLine("int=>" + v1);//1
Console.WriteLine("name=>" + v2);//Doing
Console.WriteLine("text=>" + v3);//进行中
Console.WriteLine("");
int n1 = 1;//转换成功
int n2 = 5;//转换失败
string s1 = "Doing";//转换成功
string s2 = "DDDD";//转换失败
List<object> lst = new List<object> { n1, n2, s1, s2, };
foreach (var item in lst)
{
try
{
var e = item.ToString().ToEnum<TypeEnum>();
Console.WriteLine($"{item} => 转换成功");
}
catch (Exception ex)
{
Console.WriteLine($"{item} => 转换失败,{ex.Message}");
}
}
Console.WriteLine("");
foreach (TypeEnum value in Enum.GetValues(enumType))
{
string name = Enum.GetName(enumType, value);
var fieldInfo = enumType.GetField(name);
var attrs = fieldInfo.GetCustomAttributes(typeof(TextAttribute), false);
if (attrs.Length == 1)
{
/*
Value: 1, Name: Doing, Text: 进行中
Value: 2, Name: Done, Text: 完成
Value: 9, Name: Deleted, Text: 已被删除
*/
Console.WriteLine($"Value: {(int)value}, Name: {name}, Text: {((TextAttribute)attrs[0]).Value}");
}
}
}
结果
int=>1
name=>Doing
text=>进行中
1 => 转换成功
5 => 转换失败,5 转换失败
Doing => 转换成功
DDDD => 转换失败,DDDD 转换失败
Value: 1, Name: Doing, Text: 进行中
Value: 2, Name: Done, Text: 完成
Value: 9, Name: Deleted, Text: 已被删除
ok
