C# 如何在其他类中获取textBox的值?
我的主要课程是Form1:C# 如何在其他类中获取textBox的值?,c#,winforms,C#,Winforms,我的主要课程是Form1: public partial class Form1 : Form { public Form1() { InitializeComponent(); } public void GetLengthFirst_Click(object sender, EventArgs e) { textBox.Text = "123"; } } 还有我自己的班级: class Arr { ///
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void GetLengthFirst_Click(object sender, EventArgs e)
{
textBox.Text = "123";
}
}
还有我自己的班级:
class Arr
{
/// in my opinion this should be done like this...
int Lenght = Convert.toInt32(Form1.textBox.Text);
int[] nums = new int[Lenght];
}
但是我的想法没有实现如果没有,你就无法访问另一个类的成员。 此外,成员必须是或至少是(可以在同一程序集中访问)。 因此,如果成员不是静态的,你应该告诉你的第二个类你的成员在哪里。这就是所谓的阶级适航性 因此,在你的情况下:
public partial class Form1 : Form {
public Form1() {
// tell to your second class where's your member
Arr arr = new Arr(this);
InitializeComponent();
}
public void GetLengthFirst_Click(object sender, EventArgs e) {
textBox.Text = "123";
}
}
class Arr {
private Form1 _form1;
public Arr(Form1 f) {
// Access to the members of your main class
_form1 = f;
int Lenght = Convert.toInt32(_form1.textBox.Text);
int[] nums = new int[Lenght];
}
}如果其他类的成员不是,则无法访问他们。 此外,成员必须是或至少是(可以在同一程序集中访问)。 因此,如果成员不是静态的,你应该告诉你的第二个类你的成员在哪里。这就是所谓的阶级适航性 因此,在你的情况下:
public partial class Form1 : Form {
public Form1() {
// tell to your second class where's your member
Arr arr = new Arr(this);
InitializeComponent();
}
public void GetLengthFirst_Click(object sender, EventArgs e) {
textBox.Text = "123";
}
}
class Arr {
private Form1 _form1;
public Arr(Form1 f) {
// Access to the members of your main class
_form1 = f;
int Lenght = Convert.toInt32(_form1.textBox.Text);
int[] nums = new int[Lenght];
}
}表单与任何其他类一样。如果要从类的实例获取值,必须a)引用该实例,b)使该值可用(例如,
public
)。无论如何,您的Arr
类不应该引用表单,只应该告诉它Length
的值是什么,以及(大概)数组将使用什么值。表单与任何其他类一样。如果要从类的实例获取值,必须a)引用该实例,b)使该值可用(例如,public
)。无论如何,您的Arr
类不应该引用表单,应该告诉它Length
的值是什么,以及(大概)数组将使用什么值。