我在FormMain : Form
中有此代码
如何实施OpenForm
方法以允许我打开任何类型的Form
?
// the method in question
void OpenFrom<T>()
{
// How to implement this generic method to get rid of OpenForm1() and OpenForm2() ???
}
// Open Form1 instance
void OpenForm1()
{
new Form1().Show();
}
// Open Form2 instance
void OpenForm2()
{
new Form2().Show();
}
OpenForm<Form1>(); // instead of OpenForm1()
OpenForm<Form2>(); // instead of OpenForm2()
答案 0 :(得分:9)
这里有你如何去
void OpenFrom<T>() where T : Form, new()
{
new T().Show();
}