1

请考虑以下代码:

[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”,因为它不是委托类型

哪里有问题?

4

1 回答 1

1

在你的最后一个例子中,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);
于 2013-03-30T15:27:52.583 回答