我有大量的表单都来自一个名为FormBase
的基类。要激活/显示它们,我使用以下通用方法:
public T ShowForm<T>() where T : FormBase, new()
{
FormBase form = _activeForms.FirstOrDefault(f => f is T);
if (form != null)
form.BringToFront();
else
{
form = new T();
IListView view = form as IListView;
if (view != null)
view.ParentView = this;
_activeForms.Add(form);
form.MdiParent = this;
form.Show();
}
return (T)form;
}
现在我想使用字典,以便我可以轻松地添加更多表单而无需维护巨大的switch
语句。
是否可以使用Dictionary<string, Type>
之类的字典并以某种方式将Type传递给泛型方法?
答案 0 :(得分:1)
是的,您可以使用反射:
var formType = typeof(SomeForm); // substitute with read from dictionary
// Get ShowForm<T>
var showFormMethod = typeof(YourClass).GetMethod("ShowForm");
// Convert to ShowForm<SomeForm>
var showFormMethodSpecific = showFormMethod.MakeGenericMethod(formType);
// Call method
var yourClass = new YourClass(); // holder of ShowForm
object form = showFormMethodSpecific.Invoke(yourClass, null);
// form is now of type SomeForm
答案 1 :(得分:0)
在我看来,当泛型方法应该包装非泛型方法时就是这种情况。请考虑以下代码:
private FormBase ShowForm(Type formType)
{
FormBase form = _activeForms.FirstOrDefault(f => f.GetType() == formType);
if (form != null)
form.BringToFront();
else
{
form = (FormBase)Activator.CreateInstance(formType);
IListView view = form as IListView;
if (view != null)
view.ParentView = this;
_activeForms.Add(form);
form.MdiParent = this;
form.Show();
}
return form;
}
public T ShowForm<T>() where T : FormBase, new()
{
return (T)ShowForm(typeof(T));
}
然后,当表单类型静态未知时,您可以调用方法的非泛型版本:
var form = ShowForm(typeof(SomeForm));