简体   繁体   English

C#替代(作为Form1的Application.OpenForms [0])

[英]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? 有没有更好的方法来调用someMethod?

If your Class1 instance doesn't already have a reference to the Form1 instance then there is not other way. 如果您的Class1实例还没有对Form1实例的引用,则没有其他方法。 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? 首先,如果该Class1对象需要直接影响该Form1实例,那么为什么它还没有该引用呢? Where did that Class1 object come from? 该Class1对象来自何处? Most likely the Form1 instance created it. Form1实例很可能创建了它。 If so, why didn't Form1 pass a reference to itself into the Class1 object when it was created? 如果是这样,为什么在创建Form1时不将对自身的引用传递给Class1对象?

Secondly, why is that Class1 object directly affecting the Form1 instance anyway? 其次,为什么该Class1对象仍然直接影响Form1实例? Most likely a better design would be for the Class1 object to raise an event that Form1 can handle and then affect itself. 最有可能的更好的设计是使Class1对象引发Form1可以处理然后影响自身的事件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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