为什么局部变量在timer_click事件中变空?

时间:2016-10-18 11:04:21

标签: c# timer webforms

当我以编程方式调用Timer1_Tick(null,null)时,消息变为空? 如何解决此问题OnMessageReceieve在事件触发时调用。

string message = string.Empty;
public void OnMessageReceieve(string message)
{
   //  I have a message in message variable
   txtMessage.Text += message;
   Timer1.Enabled = true;
   Timer1_Tick(null, null);
   // UpdatePanel1.Update();                  
}

protected void Timer1_Tick(object sender, EventArgs e)
{
   //message variable gets empty here?
   if (!string.IsNullOrEmpty(message))
   {
      txtMessage.Text += message;
   }                
}

2 个答案:

答案 0 :(得分:8)

您对此处声明的成员 message感到困惑:

string message = string.Empty;

使用参数您(意外地?)命名相同的message

OnMessageReceive方法中,您不需要设置成员值,但在Timer1_Tick内访问该成员。

立即解决方案是将成员设置为OnMessageReceive

public void OnMessageReceieve(string message)
{
     txtMessage.Text += message;

     // set member!!
     this.message = message;

     Timer1.Enabled = true;
     Timer1_Tick(null, null);
     // UpdatePanel1.Update();          
}

答案 1 :(得分:0)

string message = string.Empty; //Never change.

public void OnMessageReceieve(string message)
{
   //  I have a message in message variable (this is a parameter, not a field class)
   txtMessage.Text += message;
   Timer1.Enabled = true;
   Timer1_Tick(null, null);
   // UpdatePanel1.Update();                  
}

protected void Timer1_Tick(object sender, EventArgs e)
{
   //message variable gets empty here?
   if (!string.IsNullOrEmpty(message)) //<-- this.message
   {
      txtMessage.Text += message;
   }                
}
  

溶液:

string message = string.Empty;
public void OnMessageReceieve(string message)
{
   //  I have a message in message variable
   this.message = message; //<-- Add this line.
   txtMessage.Text += message;
   Timer1.Enabled = true;
   Timer1_Tick(null, null);
   // UpdatePanel1.Update();                  
}

protected void Timer1_Tick(object sender, EventArgs e)
{
   //message variable gets empty here?
   if (!string.IsNullOrEmpty(message))
   {
      txtMessage.Text += message;
   }                
}