簡體   English   中英

根據枚舉名稱將String轉換為Enum

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM