我在C#中创建了一个函数:
private void customShow(Form someForm, Type formType) {
if (someForm == null || someForm.IsDisposed) someForm = (Form)Activator.CreateInstance(formType);
someForm.StartPosition = FormStartPosition.CenterScreen;
someForm.MdiParent = this;
someForm.Show();
someForm.WindowState = FormWindowState.Maximized;
}
然后我想这样做:
private void mnuKategori_Click(object sender, EventArgs e) {
customShow(frmKategori, typeof(Master.FrmKategori));
frmKategori.isCRUD = true;
}
方法的第二行失败,因为变量frmKategori在方法执行后仍为null。如果我将“someForm”参数引用到引用中,它也会失败,因为看起来C#不支持带有“ref”和“out”关键字的多态性。有没有人对此提出建议? 提前感谢您的回复。
答案 0 :(得分:5)
也许是泛型?
private void customShow<T>(ref T someForm) where T : Form, new()
{
if (someForm == null || someForm.IsDisposed) someForm = new T();
someForm.StartPosition = FormStartPosition.CenterScreen;
someForm.MdiParent = this;
someForm.Show();
someForm.WindowState = FormWindowState.Maximized;
}
然后我想这样做:
private void mnuKategori_Click(object sender, EventArgs e)
{
customShow(ref frmKategori);
frmKategori.isCRUD = true;
}
答案 1 :(得分:2)
为什么不简单地让customShow返回一个新的Form实例,而不是填写ref / out参数?没有理由有一个带有void函数的单一输出参数。
顺便说一句,我还会将customShow
替换为buildCustomForm
,并将实际的Show()
方法保存到最后。否则可能会令人困惑。