該函數將加載一個程序集,讓用戶從列表中選擇一個表單,然後嘗試調用它。如果成功,則返回表單。如何向構造函數提供參數,事先不知道?
我的問題是如何實例化具有預期類型的參數的構造函數。 如果構造函數期望List<string>
應該提供一個空的List<String>
,而不僅僅是null。
什麼想法?
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;
}
如果它所希望的'IList'? – dasblinkenlight
你想達到什麼目的?假設構造函數需要一個非空的列表,你應該添加到列表中以使其工作嗎?或者你是否知道所有的ctors只有基元,可以爲空但不爲空的集合,或者具有這種構造器的對象實例?在這種情況下,它可能會運行 –
boiut讓用戶選擇值 - 沒有辦法計算出什麼_sensible_值使用。例如。一個空列表可能會被調用 –