Linking enum value with localized string resource

前端 未结 5 523
终归单人心
终归单人心 2021-01-02 18:15

Related: Get enum from enum attribute

I want the most maintainable way of binding an enumeration and it\'s associated localized string values to something.

5条回答
  •  被撕碎了的回忆
    2021-01-02 18:28

    I do mapping to resourse in the following way: 1. Define a class StringDescription with ctor getting 2 parameters (type of resourse and it's name)

    [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
    class StringDescriptionAttribute : Attribute
    {
        private string _name;
        public StringDescriptionAttribute(string name)
        {
            _name = name;
        }
    
        public StringDescriptionAttribute(Type resourseType, string name)
        {
                _name = new ResourceManager(resourseType).GetString(name);
    
        }
        public string Name { get { return _name; } }
    }
    
    1. Create a resourse file for either culture (for example WebTexts.resx and Webtexts.ru.resx). Let is be colours Red, Green, etc...

    2. Define enum:

      enum Colour{ [StringDescription(typeof(WebTexts),"Red")] Red=1 , [StringDescription(typeof(WebTexts), "Green")] Green = 2, [StringDescription(typeof(WebTexts), "Blue")] Blue = 3, [StringDescription("Antracit with mad dark circles")] AntracitWithMadDarkCircles

      }

    3. Define a static method getting resource description via reflection

      public static string GetStringDescription(Enum en) {

          var enumValueName = Enum.GetName(en.GetType(),en);
      
          FieldInfo fi = en.GetType().GetField(enumValueName);
      
          var attr = (StringDescriptionAttribute)fi.GetCustomAttribute(typeof(StringDescriptionAttribute));
      
          return attr != null ? attr.Name : "";
      }
      
    4. Eat :

      Colour col; col = Colour.Red; Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US");

          var ListOfColors = typeof(Colour).GetEnumValues().Cast().Select(p => new { Id = p, Decr = GetStringDescription(p) }).ToList();
      
          foreach (var listentry in ListOfColors)
              Debug.WriteLine(listentry.Id + " " + listentry.Decr);
      

提交回复
热议问题