2017-05-04 83 views
0

我一直在寻找一种方式来获得一个枚举的替代值提取备用的数据,并引用这个答案我需要一个优雅的方式来从一个枚举

https://stackoverflow.com/a/10986749/5122089

这使用描述属性分配一个值,然后一个方法用于提取经如此

public static string DescriptionAttr<T>(this T source) { 
    FieldInfo fi = source.GetType().GetField(source.ToString()); 

    DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
     typeof(DescriptionAttribute), false); 

    if (attributes != null && attributes.Length > 0) return attributes[0].Description; 
else return source.ToString(); } 

只有我不幸卡在使用.NET 3.5 Compact Framework的黑暗时代,并没有出现有System.ComponentModel.DescriptionAttribute

访问可能有人给我一个提示如何得到这样的工作。 ..

+0

您可以轻松地实现自己的自定义属性,这是你可能需要在这里做什么。 – Crowcoder

回答

1

我不确定这是你要找的。我只是做了对原始代码一些变化:

static class MyClass 
{ 
    public static string DescriptionAttr<T>(this T source, Type attrType, string propertyName) 
    { 
     FieldInfo fi = source.GetType().GetField(source.ToString()); 

     var attributes = fi.GetCustomAttributes(attrType, false); 

     if (attributes != null && attributes.Length > 0) 
     { 
      var propertyInfo = attributes[0].GetType().GetProperty(propertyName); 

      if (propertyInfo != null) 
      { 
       var value = propertyInfo.GetValue(attributes[0], null); 
       return value as string; 
      } 
     } 
     else 
      return source.ToString(); 

     return null; 
    } 
} 

public enum MyEnum 
{ 
    Name1 = 1, 
    [MyAttribute("Here is another")] 
    HereIsAnother = 2, 
    [MyAttribute("Last one")] 
    LastOne = 3 
} 

class MyAttribute : Attribute 
{ 
    public string Description { get; set; } 

    public MyAttribute(string desc) 
    { 
     Description = desc; 
    } 
} 

用法:

var x = MyEnum.HereIsAnother.DescriptionAttr(typeof(MyAttribute), "Description"); 
+0

事实上,这正是我正在寻找的东西。我非常感谢您花时间来演示。 – axa

+0

这些属性[0]并不优雅。不管怎样,你可能都想改变它。将问题标记为有效,请 – user1845593

+0

确实我已经大大地重构了答案,但它已启发我如何应用自定义属性以及反映和挖掘信息。我想我会让它坐下来看看其他人提出的 – axa

相关问题