簡體   English   中英

使用反射查找具有接口參數的構造函數

[英]Using reflection to find constructors that have interface parameters

我正在加載我的應用程序域中的所有程序集,然后嘗試查找具有某種基本類型的程序集,並且所有這些程序集的構造函數都具有一個接口作為構造函數參數。 我有以下代碼,但無法確定如何告訴它查找接口參數。

var assembliesWithPluginBaseInThem = AppDomain.CurrentDomain.GetAssemblies()
    .Where(x=>x.GetTypes().Where(y=>y.BaseType== typeof(PluginBase) &&
     y.GetConstructor(new Type[]{typeof(interface)})
var types =
    from a in AppDomain.CurrentDomain.GetAssemblies()
    from t in a.GetTypes()
    where t.GetConstructors()
                 .Any(c => c.GetParameters()
                              .Any(p => p.ParameterType.IsInterface))
    select t;

這樣的事情怎么樣:

var assembliesWithPluginBaseInThem = AppDomain.CurrentDomain.GetAssemblies()
    .Where(x =>
        x.GetTypes().Any(y =>
            typeof(PluginBase).IsAssignableFrom(y) &&
            y.GetConstructors().Any(z =>
                z.GetParameters().Count() == 1 && // or maybe you don't want exactly 1 param?
                z.GetParameters().All(a => a.ParameterType.IsInterface)
            )
        )
    );

檢查是某個類型的子類中的一個類,我建議您使用

yourClass.IsSubclassOf(typeof(parentClass))

因此應如下所示:

var assembliesWithPluginBaseInThem = AppDomain.CurrentDomain.GetAssemblies()
    .Where(x=>x.GetTypes().Where(y=>y.IsSubclassOf(typeof(PluginBase)) &&
     y.GetConstructor.Any(c => c.GetParameters()
                              .Any(p => p.ParameterType.IsInterface)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM