I'm trying to get a list of classes that implement an interface and then at some later point in the program, instantiate these classes and pass in parameters to their constructors.
In a previous Stack Overflow page, I saw this code that instantiated the classes with an empty constructor:
var preprocessors = from t
in Assembly.GetExecutingAssembly().GetTypes()
where t.GetInterfaces()
.Contains(typeof(Preprocessing))
&& t.GetConstructor(Type.EmptyTypes) != null
select Activator.CreateInstance(t) as Preprocessing;
But I don't want some classes to be instantiated without passing some kind of parameter to the constructor (the parameter is obtained in a for loop so I have to wait until I instantiate it).
I tried doing just this to get the list of classes to be instantiated:
var preprocessors = from t
in Assembly.GetExecutingAssembly().GetTypes()
select t.GetInterfaces()
.Contains(typeof(Preprocessing))
But after doing this, I wasn't sure how to access the classes and instantiate them. Would really appreciate some guidance on this. Thanks!!
Edit:
I can't figure out what to put in the Activator.CreateInstance(...)
parentheses. I tried putting something like this:
foreach (var sim in similarities)
{
var a = Activator.CreateInstance(sim, preprocessedData) as Preprocessing;
But that is throwing an error, most likely because preprocessedData
is a DenseMatrix
object (from the MathNet Numerics library). Is there any way to send a DenseMatrix
as parameter and not an array?