Ler*_*ica 1 c# generics winforms
我正在创建一个MDI form,我有一个加载不同形式的方法.现在我需要做一些修改 - 我需要添加从另一个子窗体中调用一个子窗体的功能.
因为我需要在几个不同的地方使用它,所以我创建了一个新类,其中所有需要此功能的类都继承.我希望把它与一般类型的工作,所以我可以通过我可能需要像每一个窗体类LoadAForm(MyForm1)或LoadAForm(MyForm2)等..我希望我很清楚我想要的最终结果.
我试过这个:
protected void LoadAForm<T>(ref T sender)
{
MainForm frm = this.MdiParent as MainForm;
T temp;
if (frm != null)
{
sender = SingletonFormProvider.GetInstance<temp>(frm, true);
sender.MdiParent = frm;
sender.Dock = DockStyle.Fill;
sender.Show();
}
}
Run Code Online (Sandbox Code Playgroud)
这不起作用.但是当我在方法中使用时,我几乎没有使用泛型的经验,所以我不知道如何继续.
我使用这种语法得到的错误是The type or namespace "temp" could not be found...". I'm not even sure that this is the way to do it.GetInstance <>`必须采用与我正在调用的表单类型相同类型的参数.
您需要使用type参数,而不是变量名称:
sender = SingletonFormProvider.GetInstance<T>(frm, true);
Run Code Online (Sandbox Code Playgroud)
另外,为确保T有效(如您的评论所示),您需要限制它:
protected void LoadAForm<T>(ref T sender) where T : Form
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |