2015-06-22 207 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的課程。