简体   繁体   English

使用反射查找具有接口参数的构造函数

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

I am loading up all assemblies in my app domain and then trying to find those of a certain base type and all also whose constructors have a interface as a constructor argument. 我正在加载我的应用程序域中的所有程序集,然后尝试查找具有某种基本类型的程序集,并且所有这些程序集的构造函数都具有一个接口作为构造函数参数。 I've got the below code but can't work out how you tell it to find 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;

How about something like this: 这样的事情怎么样:

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)
            )
        )
    );

to check is a class in a subclass of a certain type I would suggest you to use 检查是某个类型的子类中的一个类,我建议您使用

yourClass.IsSubclassOf(typeof(parentClass))

so it should look like the below: 因此应如下所示:

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