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

查看:412
本文介绍了C#替代(作为Form1的Application.OpenForms [0])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以已经打开的形式调用方法时,是否有以下代码的更好替代方法?

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:

表单代码:

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

类代码:

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

是否有更好的方法来调用someMethod?

Is there a better way to call someMethod?

推荐答案

如果您的Class1实例尚未引用Form1实例,则没有其他方法.不过,这有几个问题.

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.

首先,如果该Class1对象需要直接影响该Form1实例,那么为什么它还没有该引用呢?该Class1对象来自何处? Form1实例很可能创建了它.如果是这样,为什么Form1在创建时不将对自身的引用传递给Class1对象?

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?

第二,为什么该Class1对象仍然直接影响Form1实例?最好的设计可能是让Class1对象引发Form1可以处理然后影响自身的事件.

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.

这篇关于C#替代(作为Form1的Application.OpenForms [0])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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