C# 如何从这个类中调用另一个类的方法?
我有一个带有文本框和确定按钮的表单。我有另一个类(名为AnotherClass),它在表单类之前实例化。我正在另一个类中创建表单类的新实例,向用户显示表单,并在文本框中接受一些双值。单击OK按钮后,我想调用另一个类中的方法,该类使用文本框的文本作为参数。我应该怎么做?请提供帮助。如果我正确理解了您的问题,您有一个winform情况,您希望在另一个类中访问textbox值或textbox 如果是这样的话,C# 如何从这个类中调用另一个类的方法?,c#,class,delegates,C#,Class,Delegates,我有一个带有文本框和确定按钮的表单。我有另一个类(名为AnotherClass),它在表单类之前实例化。我正在另一个类中创建表单类的新实例,向用户显示表单,并在文本框中接受一些双值。单击OK按钮后,我想调用另一个类中的方法,该类使用文本框的文本作为参数。我应该怎么做?请提供帮助。如果我正确理解了您的问题,您有一个winform情况,您希望在另一个类中访问textbox值或textbox 如果是这样的话, public class AnotherClass { public void Yo
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);
}
我认为有两种方法可以解决这个问题 第一个: 在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 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() //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);
}
}
private void openForm()
{
FormClass fc = new FormClass(this);
fc.ShowDialog();
}
public void YourMethodInAnotherClass(string txt)
{
//Do you work
}
第二种解决方案(使用参数):
在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 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() //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);
}
}
private void openForm()
{
FormClass fc = new FormClass(this);
fc.ShowDialog();
}
public void YourMethodInAnotherClass(string txt)
{
//Do you work
}
非常不清楚的解释。如果我理解正确:使用参数(
public void MyMethod(string txtBoxText){}
)在AnotherClass
中创建一个公共方法,单击事件+1会调用该方法,因为它太幼稚。但是试着继续,用一段代码正确地解释你的问题,我想他只想要值,而不是文本框本身。问题是,你创建了另一个类的新对象。我想那不是他想要的