在程序持续时间内保存用户输入

时间:2013-08-04 19:46:34

标签: c# .net variables client

我想知道如何在程序的持续时间内保存用户输入。

我的代码:

struct client
{
    public string points;//to collect the points from a textbox

    public int  x;//variable used to temporarily save the input from the textbox
    public int will;//used to store his points until the end of the program
    public int steph;//used to store here points until the end of the program
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button3_Click(object sender, EventArgs e)
    {
      client ob = new client();//instance of client
      ob.points = textBox1.Text;             
      ob.x  = Convert.ToInt32(ob.points);//conversion
      MessageBox.Show(ob.x.ToString());//used to confirm points
      button1.Enabled = true;//enables button to show where the points should go
      button2.Enabled = true;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        client ob = new client();
        ob.points = textBox1.Text;           
        ob.x = Convert.ToInt32(ob.points);
        ob.will = ob.will + ob.x;
        MessageBox.Show(ob.will.ToString());//actually adding the points to him
    }

    private void button2_Click(object sender, EventArgs e) 
    {
        client ob = new client();
        ob.points = textBox1.Text;
        ob.x = Convert.ToInt32(ob.points);
        ob.steph = ob.steph + ob.x;// actually adding the points to her
        MessageBox.Show(ob.steph.ToString());
    }
}

我被告知我需要添加三个客户端实例,但这就是他们给我的所有信息。如果你告诉我,请你深入了解你的答案。另外如果有办法让代码更有效,请告诉我。

2 个答案:

答案 0 :(得分:2)

你的问题是

client ob = new client();//instance of client

这一行每次都会创建一个 new 客户端实例,你要找的是单例类

public sealed class Client
{
   private static readonly Client instance = new Client();

   private Client(){}

   public static Client Instance
   {
      get 
      {
         return instance; 
      }
   }
   public int  X {get;set;}
}

然后,当您需要您的客户时,请致电

Client.Instance
Clienet.Instance.X

依旧......

有关详细信息,请参阅this

答案 1 :(得分:0)

如果我理解了这个问题,我认为你可以使用全局类变量。 它可以是:
List<Client> clients并且您将在每个按钮后添加新客户端到全局List<Client>