如何从这个类中调用另一个类的方法?

时间:2013-09-15 19:38:36

标签: c# class delegates

我有一个带有 TextBox 的表单和一个 OK按钮。我有另一个类(名为AnotherClass),它在Form类之前被实例化。我正在创建一个新的AnotherClass中Form类的实例,向用户显示表单并在文本框中接受一些double值。单击确定按钮后,我想调用 AnotherClass 中的方法,该方法使用文本框的文本作为参数。我该怎么办?请帮忙。

2 个答案:

答案 0 :(得分:0)

如果我理解你的问题,你有一个winform情况,你想要在另一个班级中访问文本框值或文本框。

如果是这样的话,

public class AnotherClass
{
    public void YourMethodThatAccessTextBox(TextBox t)
    {
            // do something interesting with t;
    }
}

In your OK button

ok_click
{
   AnotherClass ac = new AnotherClass().YourMethodThatAccessTextBox(txtValue);
}

答案 1 :(得分:0)

我看到两种解决方法

第一个:

在FormClass中:

public string txt { get; set; } //A so called property
private void OK_button_Click(object sender, EventArgs e)
{
    txt = textBox.Text;
    this.DialogResult = System.Windows.Forms.DialogResult.OK;
    this.Close();
}

在AnotherClass中:

private void openForm() //Method in AnotherClass where you create your object of your FormClass
{
   FormClass fc = new FormClass ();
   if (fc.ShowDialog() == System.Windows.Forms.DialogResult.OK)
   {
      YourMethodInAnotherClass(fc.txt);
   }
}

第二个解决方案(使用参数):

在FormClass中:

AnotherClass anotherClass = null;
public FormClass(AnotherClass a) //Constructor with parameter (object of your AnotherClass)
{
    InitializeComponent();
    anotherClass = a;
}

private void OK_button_Click(object sender, EventArgs e)
{
    anotherClass.YourMethodInAnotherClass(textBox.Text);
    this.Close();
}

在AnotherClass中:

private void openForm()
{
    FormClass fc = new FormClass(this);
    fc.ShowDialog();
}

public void YourMethodInAnotherClass(string txt)
{
    //Do you work
}