简体   繁体   中英

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM