C# alternative to (Application.OpenForms[0] as For

2019-09-02 18:49发布

is there a better alternative to the following code When calling a method in an already open form?

(Application.OpenForms[0] as Form1).someMethod();

That line of code is of course being executed in a class.

to make it more clear here is an example:

Form Code:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public void someMethod()
        {
            //do stuff
        }
    }

Class Code:

class Class1
{
    public void aMethod()
    {
        (Application.OpenForms[0] as Form1).someMethod();
    }
}

Is there a better way to call someMethod?

标签: c# forms
2条回答
叼着烟拽天下
2楼-- · 2019-09-02 19:12

If your Class1 instance doesn't already have a reference to the Form1 instance then there is not other way. That begs a couple of questions though.

Firstly, if that Class1 object needs to directly affect that Form1 instance then why doesn't it already have that reference? Where did that Class1 object come from? Most likely the Form1 instance created it. If so, why didn't Form1 pass a reference to itself into the Class1 object when it was created?

Secondly, why is that Class1 object directly affecting the Form1 instance anyway? Most likely a better design would be for the Class1 object to raise an event that Form1 can handle and then affect itself.

查看更多
聊天终结者
3楼-- · 2019-09-02 19:20

You could always just provide Class1 with the instance of the form.

查看更多
登录 后发表回答