将变量从用户窗体传递到类中

本文关键字:窗体 变量 用户 | 更新日期: 2023-09-27 18:30:06

我经常遇到这样的问题,我并不真正理解如何将用户表单变量传递到类中。例如,我有一个按钮:

private void button1_Click(object sender, EventArgs e)
{
    DoStuff();
}

以及表单类中的方法:

DoStuff()
{
    Class123 myclass = new Class123();
}

...
...
class Class123
{
    //how do i pass for example in myotherClass whether or not my checkbox on the userform is checked? i dont want to have to pass from method to method to class to class. what is the logical/smart way of handling this?
    ClassData myotherClass = new ClassData();
}

例如,我如何在myotherClass中传递用户表单上的复选框是否被选中?我不想必须从一个方法传递到另一个方法,再传递到一个类。处理此问题的逻辑/智能方式是什么?

将变量从用户窗体传递到类中

我想您正在寻找函数参数:

// notice the declared function argument isMyCheckboxChecked
DoStuff(bool isMyCheckboxChecked)
{
    Class123 myclass = new Class123(isMyCheckboxChecked);
}
private void button1_Click(object sender, EventArgs e)
{
    // passing the state of the checkbox to DoStuff as an argument
    DoStuff(chkMyCheckbox.Checked);
}

class Class123
{
     readonly ClassData myotherClass = new ClassData();
     Class123(bool isMyCheckboxChecked) 
     { 
          myOtherClass.isMyCheckboxChecked = isMyCheckboxChecked;
     }
}

我可以在这里看到一些东西。张贴的代码相当模糊,所以很难说正确答案是什么。

  1. 如果myOtherClass需要知道当复选框更改时是否选中了复选框,那么您可能应该考虑使用订阅者模式。

  2. 但是,如果您的意思是只需要知道DoStuff()运行时是否选中了复选框,那么传递变量并没有错。事实上,传递变量是首选方式——这就是变量存在的目的。也就是说,您需要智能地传递变量;如果你发现你只是不断地在类之间抛出参数,那就是代码设计不好的迹象。如果您需要将一些参数传递给myClass来告诉它该做什么,请将它们构建到自己的(描述性命名的)类中,并将该类传递给myClass的构造函数,而不是一长串参数。

我不同意这种方法
任何"智能"方法,如果存在的话,都将打破面向对象编程的黄金法则。对象是一个自包含的数据项,只能以可控的方式访问或更改。这可以防止副作用,这是过程代码中的一个常见问题,因为数据是全局可访问的。在OOP中,对象只能通过调用它们的方法来接收消息或向其他对象发送消息。

编辑:显示一种方法来做到这一点

public static class MyApp
{
    public static bool MyCheckBox {get; set;}
}

在你的doStuff

MyApp.MyCheckBox = this.checkBox1.Checked;

在myOtherClass 的方法内部

   if(MyApp.MyCheckBox == true)
   ...

这与在过去的过程语言中使用全局变量是一样的。这为难以跟踪的错误铺平了道路,并创建了状态模式,使应用程序难以维护