【问题标题】:How to call method of another class from this class ?如何从这个类中调用另一个类的方法?
【发布时间】:2013-09-19 22:25:47
【问题描述】:

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

【问题讨论】:

  • 解释不清楚。
  • 如果我理解正确:在 AnotherClass 中创建一个公共方法,并带有一个由点击事件调用的参数 (public void MyMethod(string txtBoxText){ })
  • +1 表示天真。但请继续尝试,用一段代码正确解释您的问题

标签: c# class delegates


【解决方案1】:

我看到了两种解决方法

第一个:

在表单类中:

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();
}

在另一个类中:

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);
   }
}

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

在表单类中:

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();
}

在另一个类中:

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

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

【讨论】:

    【解决方案2】:

    如果我正确理解了你的问题,你有一个 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);
    }
    

    【讨论】:

    • 我猜他只想要值而不是 TextBox 本身
    • 问题是,你创建了另一个类的新对象。我想这不是他想要的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2020-09-03
    • 2016-10-12
    • 2019-06-22
    相关资源
    最近更新 更多