从属性属性获取数据

时间:2011-09-12 15:11:32

标签: c# reflection attributes

我有一个使用自定义属性的视图模型,例如

public int Id { get; set; }
public string Name { get; set; }
[IsEnumeration(typeof(CaseStatus))]
public string Status { get; set; }

IsEnumeration是一个自定义属性,它将Enumeration超类作为参数(实际上它需要任何类型,但这并不重要,因为没有其他人会使用它)

public class IsEnumerationAttribute : Attribute
{
    public Type Enumeration;
    public IsEnumerationAttribute(Type enumeration)
    {
        Enumeration = enumeration;
    }
}

我想要的是能够获得为任何参数指定的类型。目前我的代码如下所示:

    public T EnumerationValuesToDisplayNames<T>(T item) where T : new()
    {
        if (LoggedInUser.IsSuper) return item;
        var tProps = typeof (T).GetProperties()
            .Where(prop => Attribute
                 .IsDefined(prop, typeof (IsEnumerationAttribute)));

        foreach (var prop in tProps)
        {
            if (prop.GetValue(item, null) != null)
            {
                /*

    Here I look through all properties with the IsEnumerable attribute.
    I want to do something such as:
                var type = prop.GetAttribute(item, typeof(IsEnumerable));
                var displayName = Enumeration<type>.FromId(prop.GetValue(item, null));
                prop.SetValue(item, displayName);

                */
            }
        }
        return item;
    }

我希望这是有道理的,非常感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:2)

假设您的帖子中有一个如此定义的类:

public class Enumeration<T> {

  public static string FromId(string id) {
    // FromId Implmentation
  }

}

然后你应该只需要

foreach (var prop in tProps) {  
  var id=prop.GetValue(item, null);
  if (id!=null) {  
    var type = prop.GetCustomAttributes(typeof(EnumerationAttribute>,true).OfType<EnumerationAttribute>().Select(x=>x.Enumeration).First();
    var enumerationType=typeof(Enumeration<>).MakeGenericType(type);
    var fromIdMethod=enumerationType.GetMethod("FromId",BindingFlags.Public|BindingFlags.Static|BindingFlags.InvokeMethod);
    var displayName=fromIdMethod.Invoke(null,new object[] {id});
    prop.SetValue(item, displayName);  
  }  
}  

或者您可以直接在EnumerationAttribute中实现FromId方法,然后您可以直接调用它... ...

foreach (var prop in tProps) {  
  var id=prop.GetValue(item, null);
  if (id!=null) {  
    var enumAttrib = prop.GetCustomAttributes(typeof(EnumerationAttribute>,true).OfType<EnumerationAttribute>().First();
    var displayName=enumAttrib.FromId((string)id);
    prop.SetValue(item, displayName);  
  }  
相关问题