2015-10-28 60 views
1

考慮以下接口如何使用反射來獲取特定的接口類型的所有領域

public interface ISample 
public interface ISample2 : ISample 

public class A 
{ 
    [Field] 
    ISample SomeField {get; set;} 

    [Field] 
    ISample2 SomeOtherField {get; set; } 
} 

假設有不同的類,如A類和各種領域,如SomeField和SomeOtherField。 我怎樣才能得到所有這些字段其類型ISample或ISample(如ISample2)

+1

這些都是字段。這些都是屬性。 –

回答

3

您可以使用ReflectionLinq組合來這樣做衍生其它接口的列表:

var obj = new A(); 
var properties = obj.GetType().GetProperties() 
        .Where(pi => typeof(ISample).IsAssignableFrom(pi.PropertyType)) 

處理泛型時,您必須格外謹慎。但對於你,如果你想要得到的是至少有一個屬性返回的ISample一個孩子,你將不得不使用組件,例如所有的類問這是什麼應該是不錯的

,當前執行的

Assembly.GetExecutingAssembly().GetTypes() 
     .SelectMany(t => t.GetProperties().Where(pi => // same code as the sample above) 

如果你有幾個組件探測你可以使用類似這樣的東西

IEnumerable<Assembly> assemblies = .... 
var properties = assemblies 
      .SelectMany(a => a.GetTypes().SelectMany(t => t.GetProperties()...)) 
+3

您不需要'A'的實例,您可以使用'typeof(A).GetProperties()...' –

+0

@CraigW。是的,我知道我只是想要非常明確地避免任何混淆。感謝評論,儘管我真的忘了說 – Luiso

+0

如前所述,有很多類,比如A類。@ CraigW,@Luiso –

相關問題