2015-06-22 209 views
0

我有一组类实现了一个公共接口,并用业务域属性注释。在设计上,每类有不同的参数化通过属性值获取对象

[Foo(Bar=1)] 
public class EntityA : ICustomInterface 

[Foo(Bar=2)] 
public class EntityB : ICustomInterface 

[Foo(Bar=3)] 
public class EntityC : ICustomInterface 

无论是从Spring的IApplicationContext或使用老式反射,注释我怎么发现,实现ICustomInterface标注有[Foo(Bar=Y)]类?

类似Spring的Java的getBeansWithAnnotation。我不需要Spring.net,因为这些对象是原型。需要明确的是:如果我的任务不需要使用Spring在所有我很高兴与

+1

那么[this](http://stackoverflow.com/questions/26733/getting-all-types-that-implement-an-interface)和[this](http://stackoverflow.com/questions/ 607178 /如何枚举,所有类,与定制类属性)。这些问题已被无数次地问及。 –

+0

难道你不能使用[is](https://msdn.microsoft.com/en-us/library/scekt9xw.aspx)吗? – DGibbs

+0

@DGibbs谢谢但'is'运算符不适用。我的方法中没有类的实例,我将根据属性的值实例化正确的类。 –

回答

2

如果您已经获得了大会,你可以只遍历类型和检查您的条件:

var matchingTypes = 
    from t in asm.GetTypes() 
    where !t.IsInterface && !t.IsAbstract 
    where typeof(ICustomInterface).IsAssignableFrom(t) 
    let foo = t.GetCustomAttribute<FooAttribute>() 
    where foo != null && foo.Bar == Y 
    select t; 

我假设你只想要Foo.Bar的值为Y的课程。