请考虑此准则:
[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"类型。因为它不是委托类型
问题在哪里?
在上一个示例中,f
和h
都是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);