该函数将加载一个程序集,让用户从列表中选择一个表单,然后尝试调用它。如果成功,则返回表单。
我的问题是如何使用预期类型的参数实例化构造函数。如果构造函数期望应该提供List<string>
一个空值,而不仅仅是空值。List<String>
有任何想法吗?
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;
}