C#将文本框值分配给另一个文件中另一个类的变量

时间:2014-08-01 14:35:40

标签: c# .net multithreading variables methods

我创建了一个简单的表单" people" ,还有另一个文件" Information.cs"

主要用于分配文本框" txt_lname"值变量

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

                }
            }
        }
    }
}

*我可以在线程类中使用run方法中的变量值吗?如果不能那么为什么?

2 个答案:

答案 0 :(得分:3)

您必须在表单上创建Information的实例,然后将数据传递给所述实例。一个类的代码不会因为你将它添加到你的项目而神奇地执行,你必须实际创建一个类的实例。

因此,我们在表单上创建并初始化Information的实例:

public partial class people : Form
{
    private Information _information;

    public people() {
        InitializeComponent();
        _information = new Information();
    }
}

您现在可以将内容传递到Information的实例。但要做到这一点,你需要一种方法来传递它,或者在这种情况下Information需要一种方法来接收LastName。实现此目的的方法不止一种,但常见的方法是在LastName上公开Information属性:

public class Information
{
    ...
    public string LastName { get; set; }
    ...
}

现在您可以将值传递给LastName属性:

private void btn_login_Click(object sender, EventArgs e) {
    _information.LastName = txt_lname.Text;
}

注意:当您想在Information上执行run方法时,您将通过实例执行此操作,就像您设置LastName时一样:

private void btn_run_click(object sender, EventArgs e) {
    _information.run();
}

答案 1 :(得分:-3)

使信息类静态

public static class Information

在您的主要表单中,您可以像

一样使用它
Information.LastName = txt_lname.Text;

但您还需要将LastName声明为属性。所以添加

public string LastName {get; set;}

进入您的信息类。

相关问题