0

我正在尝试获取程序集中具有自定义属性的所有属性。我是这样做的,但我通过两个步骤来完成相同的验证。

前任:

abstract class XX

class Y1 : XX {
   [MyCustomAttribute(Value = "val A")]
   public int Something {get; set;}

}

class Y2 : XX {
   [MyCustomAttribute(Value = "val A")]
   public int Another {get; set;}

}

class Y3 : XX {
   [MyCustomAttribute(Value = "val B")]
   public int A1 {get; set;}

   [MyCustomAttribute(Value = "val C")]
   public int A2 {get; set;}

}

所以具有它的程序集中所有属性的列表

Something
Another
A1
A2

我用这个 linq 得到它

string attrFilter = "SomeValue";

var ts = this.GetType().Assembly.GetTypes().ToList().FindAll(c => typeof(XX).IsAssignableFrom(c) && !c.IsAbstract && !c.IsInterface);

var classes = from classe in ts
              where classe.GetProperties().ToList().FindAll(
                      property => property.GetCustomAttributes(typeof(MyCustomAttribute), false).ToList().FindAll(
                          att => typeof(MyCustomAttribute).IsAssignableFrom(att.GetType()) && (att as MyCustomAttribute).Value == attrFilter
                      ).Count > 0
                    ).Count > 0
              select classe;

这只会给我上课。所以我需要从每个类中提取属性

List<PropertyInfo> properties = new List<PropertyInfo>();
Parallel.ForEach(classes, classe => {
    var props = classe.GetProperties().ToList();
    var fks = from property in props
              where property.GetCustomAttributes(typeof(MyCustomAttribute), false).ToList().FindAll(
                          att => typeof(MyCustomAttribute).IsAssignableFrom(att.GetType()) && (att as MyCustomAttribute).Value == attrFilter
                      ).Count > 0
              select property;

    fks.ToList().ForEach(p => properties.Add(p));
});

如您所见,属性 linq 的WHERE条件与没有类列表的类查询相同。

我想知道是否可以从第一个 linq 查询中提取属性

4

1 回答 1

2

让我们分解一下。

获取所有类型:

var types = System.AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany
    ( 
        a => a.GetTypes() 
    );

对于所有类型,获取所有属性:

var properties = types.SelectMany
( 
    t => t.GetProperties() 
);

对于所有属性,获取具有所需属性的属性:

var list = properties.Where
( 
    p => p.GetCustomAttributes(typeof(Attribute), true).Any() 
);

全部一起:

var list= System.AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany( a => a.GetTypes() )
    .SelectMany( t => t.GetProperties() )
    .Where
    ( 
        p => p.GetCustomAttributes(typeof(Attribute), true).Any() 
    );
于 2018-04-04T19:52:06.377 回答