This function will load an assembly, let the user select a form from a list, and then try to invoke it. If successful, returning the form.
My problem is how to instantiate the constructor with parameters that is of the expected type.
if the constructor expect List<string>
an empty List<String>
should be supplied, not just null.
Any Ideas?
private Form SelectForm(string fileName)
{
Assembly assembly = Assembly.LoadFrom(fileName);
var asmTypes = assembly.GetTypes().Where(F => F.IsSubclassOf(typeof(Form)));
string SelectedFormName;
using (FrmSelectForm form = new FrmSelectForm())
{
form.DataSource = (from row in asmTypes
select new { row.Name, row.Namespace, row.BaseType }).ToList();
if (form.ShowDialog(this) != DialogResult.OK)
return null;
SelectedFormName = form.SelectedForm;
}
Type t = asmTypes.Single<Type>(F => F.Name == SelectedFormName);
foreach (var ctor in t.GetConstructors())
{
try
{
object[] parameters = new object[ctor.GetParameters().Length];
for (int i = 0; i < ctor.GetParameters().Length; i++)
{
parameters[i] = ctor.GetParameters()[i].DefaultValue;
}
return Activator.CreateInstance(t, parameters) as Form;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return null;
}
in order to create objects from types definitions this method works very well.
...