简体   繁体   中英

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

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?

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.

您总是可以只向Class1提供表单的实例。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM