[英]Convert String to Enum based on enum name
所以我们的枚举设置如下:
[CorrelatedNumeric(0)]
[Description("USD")]
[SequenceNumber(10)]
USD = 247
基本上,另一个函数可以为我提供string
“USD”,但不是确切的枚举,因为它的来源是Excel,我们不能让我们的用户记住枚举值;)也没有多大意义。
有没有一种方法可以让c#从“USD”变为247,因为它们的枚举设置在上面?
Enum.TryParse()
或Enum.Parse()
做你需要的吗?
Currency cValue = (Currency) Enum.Parse(typeof(Currency), currencyString);
绝对 - 通过反射构建Dictionary<string, YourEnumType>
。 只需迭代枚举中的所有字段并找到属性值,然后以这种方式构建字典。
你可以在EnumInternals
看到我在Unconstrained Melody中为描述属性做了类似的EnumInternals
:
// In the static initializer...
ValueToDescriptionMap = new Dictionary<T, string>();
DescriptionToValueMap = new Dictionary<string, T>();
foreach (T value in Values)
{
string description = GetDescription(value);
ValueToDescriptionMap[value] = description;
if (description != null && !DescriptionToValueMap.ContainsKey(description))
{
DescriptionToValueMap[description] = value;
}
}
private static string GetDescription(T value)
{
FieldInfo field = typeof(T).GetField(value.ToString());
return field.GetCustomAttributes(typeof(DescriptionAttribute), false)
.Cast<DescriptionAttribute>()
.Select(x => x.Description)
.FirstOrDefault();
}
为自己的属性类型做同样的事情。
public static object enumValueOf(string description, Type enumType)
{
string[] names = Enum.GetNames(enumType);
foreach (string name in names)
{
if (descriptionValueOf((Enum)Enum.Parse(enumType, name)).Equals(description))
{
return Enum.Parse(enumType, name);
}
}
throw new ArgumentException("The string is not a description of the specified enum.");
}
public static string descriptionValueOf(Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[]) fi.GetCustomAttributes( typeof(DescriptionAttribute), false);
if (attributes.Length > 0)
{
return attributes[0].Description;
}
else
{
return value.ToString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.