将变量从用户表单传递给类

时间:2012-04-05 22:45:48

标签: c# .net winforms

我经常遇到这个问题,我真的不明白如何将userform变量传递给类。例如,我有一个按钮:

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中传递是否检查了userform上的复选框?我不想要从方法传递到类到类。处理这个问题的逻辑/智能方法是什么?

3 个答案:

答案 0 :(得分:3)

我认为您正在寻找函数参数

// 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 :(得分:2)

我在这里可以看到一些东西。发布的代码相当模糊,因此很难说出正确的答案是什么。

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

  2. 但是,如果您只是想知道DoStuff()运行时是否检查了复选框,那么传递变量没有任何问题。实际上,传递变量是首选方式 - 它是变量的存在。也就是说,你需要智能地传递变量;如果你发现你只是不断地在各个类中抛出参数,那就是代码设计不佳的标志。如果你需要将一些参数传递给myClass来告诉它要做什么,将它们构建成自己的(描述性命名)类,并将该类传递给myClass的构造函数而不是一长串参数。

答案 2 :(得分:1)

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

编辑:展示一种方法

public static class MyApp
{
    public static bool MyCheckBox {get; set;}
}
在你的doStuff中

MyApp.MyCheckBox = this.checkBox1.Checked;

在myOtherClass的方法中

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

这与在过程语言的旧时代使用全局变量相同。这为难以跟踪的错误铺平了道路,并创建了使应用程序难以维护的状态模式