开发者

function to get an instance of a form

I want to build an build a function that does return me an already existing instance of a form.

fx = getForm(Form1);

here i get the error 'FensterTest.Form1' is a 'type' but is used like a 'variable开发者_运维技巧' So i need some casting, but i have no idea in what i need to cast.

private Form getForm(Form f)
{
  foreach (Form a in Application.OpenForms)
  {
    if (a is f)
    {
      f fx = (f)a;
      return fx;
    }
  }
  return null;
}

and wherever i use "f" i get a "type or namespace name 'f' not found"

"f fx = (f)a;" was formerly "Form1 fx = (Form1)a;" and that worked quite well, but since i do also need to use Form2 Form3, ...


You probably want to find the Form from the OpenForms collection, that is of a specified type. So you need to pass the type in - you can either pass in a Type object, or you can make the method generic so you can pass in a type parameter. Sending in a type parameter has the advantage that you can be type safe (returning the concrete type that you searched for in case you need it). Here is a generic solution:

private TForm getForm<TForm>()
    where TForm : Form
{
    return (TForm)Application.OpenForms.OfType<TForm>().FirstOrDefault();
}

Note, OfType and FirstOrDefault is a LINQ extension methods, make sure you import System.Linq. Use the method above like this:

Form f = getForm<Form1>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜