要获得您的属性,您将需要使用方法/扩展。按照这个问题和答案,你可以做这样的事情:
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");