2016-08-29 149 views
1

有对象的列表:C#获取来自列表特定属性的属性对象

List<ConfigurationObjectBase> ObjectRegistry; 

具有以下属性和上面的一些对象的与属性饰:

[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = true)] 
public sealed class PropertyCanHaveReference : Attribute 
{ 
    public PropertyCanHaveReference(Type valueType) 
    { 
     this.ValueType = valueType; 
    } 

    public Type ValueType { get; set; } 
} 

现在,我想找到其属性用该属性装饰的所有对象。

尝试下面的代码,好像我做错了:

List<ConfigurationObjectBase> tmplist = ObjectRegistry.Where(o => (o.GetType().GetProperties().Where(p => p.GetCustomAttributes(typeof(PropertyCanHaveReference), true).Length > 0))); 

感谢您的时间。

+3

不应该第二个'Where'是'Any'? –

+0

乍一看你的代码看起来是正确的(尽管你可能想要坚持约定并调用属性类“PropertyCanHaveReferenceAttribute”)。实际上会发生什么“错误”?你会得到哪些错误信息或没有结果?请提供无法运行的示例对象或[最小,完整且可验证的示例](http://stackoverflow.com/help/mcve) –

回答

1

看来你有你展示的代码行的一些语法错误。你可以将某些Where/Count组合转换为Any()。这个工作对我来说:

List<ConfigurationObjectBase> tmplist = 
     ObjectRegistry.Where(o => o.GetType().GetProperties().Any(p => 
       p.GetCustomAttributes(typeof(PropertyCanHaveReference), true).Any())).ToList(); 

所以你筛选出具有任何你的类型的属性的任何属性的所有对象。

您也可以使用通用GetCustomAttribute<T>()方法:

List<ConfigurationObjectBase> tmplist = 
     ObjectRegistry.Where(o => o.GetType().GetProperties().Any(p => 
        p.GetCustomAttribute<PropertyCanHaveReference>(true) != null)).ToList(); 

请考虑按照惯例PropertyCanHaveReferenceAttribute来命名属性类。

0

这里是一个代码来获得对象的名单,其中有它的属性饰有自定义属性:

 List<ConfigurationObjectBase> tmplist = ObjectRegistry.Where(o => 
      (o.GetType().GetProperties(System.Reflection.BindingFlags.Public | 
            System.Reflection.BindingFlags.NonPublic | 
      System.Reflection.BindingFlags.Instance).Where(
      prop => Attribute.IsDefined(prop, typeof(PropertyCanHaveReference)))).Any()).ToList(); 

您的代码将只能得到公共属性,已被装饰。上面的代码将得到:公共和非公开。

0

这System.Type的扩展方法应该工作:

public static IEnumerable<PropertyInfo> GetPropertiesWithAttribute<TAttribute>(this Type type) where TAttribute : Attribute 
{ 
    var properties = type.GetProperties(); 
    // Find all attributes of type TAttribute for all of the properties belonging to the type. 
    foreach (PropertyInfo property in properties) 
    { 
     var attributes = property.GetCustomAttributes(true).Where(a => a.GetType() == typeof(TAttribute)).ToList(); 
     if (attributes != null && attributes.Any()) 
     { 
      yield return property; 
     } 
    } 
}