Question

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, for example use "world" to get the enum value of summer. I am using Windows phone 8.1 runtime so most methods that I have found do not work.

Thanks in advance.

public enum test  
{ 
    [StringValue("hello")] 
    school, 
    [StringValue("world")] 
    summer, 
    [StringValue("fall")] 
    car 
} 

public class StringValueAttribute : Attribute 
{ 
    private string _value; 
    public StringValueAttribute(string value) 
    { 
       _value = value;
    } 

    public string Value 
    { 
       get { return _value; } 
    } 
} 
Était-ce utile?

La solution

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<T>(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<test>("world");
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top