C#将文本框值分配给另一个文件中另一个类中的变量
我创建了一个简单的表单“people”,还有另一个文件“Information.cs” 在main中,为变量指定文本框“txt_lname”值C#将文本框值分配给另一个文件中另一个类中的变量,c#,.net,multithreading,variables,methods,C#,.net,Multithreading,Variables,Methods,我创建了一个简单的表单“people”,还有另一个文件“Information.cs” 在main中,为变量指定文本框“txt_lname”值 String lastname = txt_lname.Text; 然后我想在“信息类”中使用这个值(它是一个线程类) 我如何使用它 (我已经评论了我想要使用该值的地方) 主表单 namespace users { public partial class people : Form { public people()
String lastname = txt_lname.Text;
然后我想在“信息类”中使用这个值(它是一个线程类)
我如何使用它
(我已经评论了我想要使用该值的地方)
主表单
namespace users
{
public partial class people : Form
{
public people()
{
InitializeComponent();
}
private void btn_login_Click(object sender, EventArgs e)
{
String lastname = txt_lname.Text;
}
}
}
信息类
namespace users
{
class Information
{
int[] idno = new int[10];
int[] age = new int[10];
string[] fname = new string[10];
// Here I want to assign txt_lname.Text value to a variable
lastname = txt_lname.Text; // This code is not working
public void run()
{
while (true)
{
for (int i = 0; i < 600; i++)
{
//Some code here
try
{
Thread.Sleep(100);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
}
}
}
}
}
}
命名空间用户
{
班级信息
{
int[]idno=新的int[10];
int[]年龄=新int[10];
字符串[]fname=新字符串[10];
//在这里,我想将txt_lname.Text值分配给一个变量
lastname=txt_lname.Text;//此代码无效
公开募捐
{
while(true)
{
对于(int i=0;i<600;i++)
{
//这里有一些代码
尝试
{
睡眠(100);
}
捕获(例外情况除外)
{
Show(例如ToString(),“Error”,MessageBoxButtons.ok取消,MessageBoxIcon.Error);
}
}
}
}
}
}
*我可以在线程类的run方法中使用变量的值吗?如果不能,为什么?将信息类设置为静态
public static class Information
在你的主要形式中,你可以像
Information.LastName = txt_lname.Text;
但是您还需要将LastName声明为属性。所以加上
public string LastName {get; set;}
进入您的信息类。您必须在表单上创建一个
信息的实例,然后将数据传递给该实例。类的代码不会因为您将其添加到项目中而神奇地执行,您必须实际创建类的实例
因此,让我们在表单上创建并初始化信息的实例
:
public partial class people : Form
{
private Information _information;
public people() {
InitializeComponent();
_information = new Information();
}
}
现在,您可以将内容传递给信息的实例。但要做到这一点,您需要一种方法来传递它,或者在本例中,信息
需要一种方法来接收姓氏。执行此操作的方法不止一种,但常用的方法是在信息
上公开LastName
属性:
public class Information
{
...
public string LastName { get; set; }
...
}
现在,您可以将该值传递给LastName
属性:
private void btn_login_Click(object sender, EventArgs e) {
_information.LastName = txt_lname.Text;
}
注意:当您想要在信息上执行run方法时,您将通过实例执行,就像设置LastName时一样:
private void btn_run_click(object sender, EventArgs e) {
_information.run();
}
txt\u lname
在哪里声明?请仔细阅读。为什么它需要是静态的?使用静态似乎很奇怪。