Parse StringValueAttribute to return Enum

后端 未结 1 1648
予麋鹿
予麋鹿 2021-01-28 11:59

I currently have a windows phone 8.1 runtime project with enums that use a string value attribute. I want to be able to get an enum value by using the string value attribute, fo

1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-28 12:14

    To get to your Attributes you will need to use a method/extension. Folowing this question and answer you can make such a thing:

    public class StringValueAttribute : Attribute
    {
        private string _value;
        public StringValueAttribute(string value)
        {
            _value = value;
        }
    
        public string Value
        {
            get { return _value; }
        }
    
        public static string GetStringValue(Enum value)
        {
            Type type = value.GetType();
            FieldInfo fi = type.GetRuntimeField(value.ToString());
            return (fi.GetCustomAttributes(typeof(StringValueAttribute), false).FirstOrDefault() as StringValueAttribute).Value;
        }
    }
    

    Then using this line of code:

    string stringTest = StringValueAttribute.GetStringValue(test.summer);
    

    will give a result of "world". (Opposite what you wanted, but hopefuly will give you an idea how to deal with the problem).

    Depending on what you want to achieve, you can probably use different methods linke: using Dictionary, struct, properties and probably different ways.

    As for parsing Enum values you can achieve it like this:

    test testValue = test.summer;
    string testString = testValue.ToString();
    test EnumValue = (test)Enum.Parse(typeof(test), testString);
    

    EDIT

    If you want to get enum from attribute, then this method (probably should be improved) should do the job:

    public static T GetFromAttribute(string attributeName)
    {
        Type type = typeof(T);
        return (T)Enum.Parse(typeof(T), type.GetRuntimeFields().FirstOrDefault(
          x => (x.CustomAttributes.Count() > 0 && (x.CustomAttributes.FirstOrDefault().ConstructorArguments.FirstOrDefault().Value as string).Equals(attributeName))).Name);
    }
    

    Usage:

    test EnumTest = StringValueAttribute.GetFromAttribute("world");
    

    0 讨论(0)
提交回复
热议问题