0

我目前有一个带有使用字符串值属性的枚举的 windows phone 8.1 运行时项目。我希望能够通过使用字符串值属性来获取枚举值,例如使用“world”来获取夏天的枚举值。我正在使用 Windows phone 8.1 运行时,所以我发现的大多数方法都不起作用。

提前致谢。

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; } 
    } 
} 
4

1 回答 1

2

要获得您的属性,您将需要使用方法/扩展。按照这个问题和答案,你可以做这样的事情:

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;
    }
}

然后使用这行代码:

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

将给出“世界”的结果。(与您想要的相反,但希望能给您一个如何处理问题的想法)。

根据您想要实现的目标,您可能可以使用不同的方法链接:使用 Dictionary、struct属性和可能不同的方式。

至于解析枚举值,您可以这样实现:

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

编辑

如果你想从属性中获取枚举,那么这个方法(可能应该改进)应该可以完成这项工作:

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);
}

用法:

test EnumTest = StringValueAttribute.GetFromAttribute<test>("world");
于 2014-04-25T05:09:56.363 回答