如何通过将表单作为变量传递来定义方法 [英] how to define method by passing form as a variable

查看:125
本文介绍了如何通过将表单作为变量传递来定义方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void changePasswordToolStripMenuItem_Click(object sender, EventArgs e)
     {
         if (Application.OpenForms.OfType<frmChangePassword>().Count() >= 1)
         {
             Application.OpenForms.OfType<frmChangePassword>().First().Activate();
         }
         else
         {
             frmChangePassword d = new frmChangePassword();
             d.MdiParent = this;
             d.Show();
         }
     }



这是我用于创建表单对象并调用它的代码

,我想要它..


this is code i am using for creating object of a form and calling it
and i want it as..

private void changePasswordToolStripMenuItem_Click(object sender, EventArgs e)
       {
         OpenForm(frmChangePassword);
       }
 private void OpenForm(Form frm)
       {

            if (Application.OpenForms.OfType<frm>().Count() >= 1)
            {
                Application.OpenForms.OfType<frm>().First().Activate();
            }
            else
            {
                frm = new frm();
                frm.MdiParent = this;
                frm.Show();
            }

       }



这样的东西,但它给了我一个错误..

frmChangePassword'是一个'类型',但用作'变量'


something like this but it gives me an Error ..
frmChangePassword' is a 'type' but is used like a 'variable'

推荐答案

您不能将表单类型传递给期望实例的方法;并且你不能使用实例来创建一个新实例:你的代码对于它究竟要做什么感到困惑。

即使你可以,它也不会很多当代码退出else条件的代码块时,就会丢弃您创建的实例,并且不再可以直接访问该应用程序。



看起来像你试图确保你只获得passowrd表单的一个实例。



我这样做的方式要简单得多:保持一个类级变量指的是frmChangePassword类的现有实例。最初为null,当你去使用它时,你会检查它。如果不为null,则激活它。

如果为null,则创建一个新实例,将其分配给变量,并为其FormClosed事件添加处理程序。在事件处理程序中,将变量设置为null。
You can't pass the type of a form to a method expecting an instance; and you can't use an instance to create a new instance: your code is confused as to what exactly it is trying to do.
And even if you could, it wouldn't be a lot of use as the instance you create is discarded as soon as code exits the code block of the else condition, and is no longer directly accessible to the application.

It looks like you are trying to ensure that you only get a single instance of the passowrd form.

The way I would do it is a lot simpler: keep a class level variable which refers to the existing instance of the frmChangePassword class. Initially null, when you go to use it, you check for that. If not null, activate it.
If it is null, create a new instance, assign it to the variable, and add a handler to it's FormClosed event. In the event handler, you set the variable back to null.


这篇关于如何通过将表单作为变量传递来定义方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆