2015-10-28 131 views
1

我有大量的表单都来自基类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

你需要'词典<字符串类型>'或'Dictionary '? – qxg

+0

你需要什么字典? –

+0

我使用了一个相当大的'switch(key)'语句,它使用'key'并基本上将其转换为'ShowForm ();'。如果我可以使用字典,我只需要在字典中添加'key'和'typeof(FooForm)'来处理我的代码中的新窗体。 – w4n

回答

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)); 
+0

非常感谢!这工作正常。看来我在这里想的太复杂了。如果我只能使用“类型”作为参数,那么通用方法并不是真的需要。 – w4n

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 
+0

谢谢!这是一个非常有趣的解决方案,它的作品!不幸的是,在我的第一次测试中,使用反射似乎相当缓慢。 – w4n

+0

你打算如何使用字典?如果我们更了解你打算如何处理它,比如你为什么拥有它,你打算如何填充它等,那么也许我可以给你一个更好的解决方案。 –