获取基于另一个属性的值的属性描述

时间:2013-03-30 11:23:13

标签: c# reflection attributes

请考虑此准则:

[ShowFieldByRole(User1 = false, User2 = false, User3 = true)]
[FieldName(Name = "Desciption1")]
public string G_Sum{set; get;}

[ShowFieldByRole(User1 = false, User2 = false, User3 = false)]
[FieldName(Name = "Desciption2")]
public string G_Sum2{set; get;}

[ShowFieldByRole(User1 = false, User2 = false, User3 = true)]
[FieldName(Name = "Desciption3")]
public string G_Sum3{set; get;}

我创建了两个自定义属性类,现在我想得到所有描述(值的 属性为Name的属性的FieldName属性的User3=true属性。

例如,根据上面的代码,我想获得Description2,Descriptio3,因为他们的User3等于true

我怎么能这样做?

感谢


修改1)

我编写了这段代码并返回Description2,Descriptio3

var My = typeof(ClassWithAttr).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                          .Where(p => p.GetCustomAttributes(typeof(FieldName), true)
                          .Where(ca => ((ShowFieldByRole)ca).User3 == true)
                          .Any()).Select(p=>p.GetCustomAttributes(typeof(FieldName),true).Cast<FieldName>().FirstOrDefault().Name);

现在我想返回[PropertyName , Name]当我以这种方式编写代码时:

    var My = typeof(ClassWithAttr).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                          .Where(p => p.GetCustomAttributes(typeof(FieldName), true)
                          .Where(ca => ((ShowFieldByRole)ca).User3 == true)
                          .Any()).ToDictionary(f => f.Name, h=>h.GetValue(null).ToString());

但是我收到了这个错误:

  

无法将lambda表达式转换为类型'System.Collections.Generic.IEqualityComparer',因为它不是委托类型

问题出在哪里?

1 个答案:

答案 0 :(得分:1)

在上一个示例中,fh都是PropertyInfo

您案例的正确代码是

var dictionay = (from propertyInfo in typeof (ClassWithAttr).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                 where propertyInfo.GetCustomAttributes(typeof (ShowFieldByRoleAttribute), true).Cast<ShowFieldByRoleAttribute>().Any(a => a.User3)
                 from FieldNameAttribute fieldName in propertyInfo.GetCustomAttributes(typeof (FieldNameAttribute), true)
                 select new { PropertyName = propertyInfo.Name, FiledName = fieldName.Name })
    .ToDictionary(x => x.PropertyName, x => x.FiledName);
使用方法链

UPD

var dictionay = typeof (ClassWithAttr).GetProperties(BindingFlags.Instance | BindingFlags.Public)
    .Where(p => p.GetCustomAttributes(typeof (ShowFieldByRoleAttribute), true).Cast<ShowFieldByRoleAttribute>().Any(a => a.User3))
    .SelectMany(p => p.GetCustomAttributes(typeof (FieldNameAttribute), true).Cast<FieldNameAttribute>(),
                (p, a) => new { PropertyName = p.Name, FiledName = a.Name })
    .ToDictionary(a => a.PropertyName, a => a.FiledName);