从一个方法传递值以在C#中的另一个方法中使用它们

时间:2015-04-18 16:10:47

标签: c# methods parameter-passing

如何使用timer_lights_status_Tick中的groupBox1_Paint方法中的值?

public Main()
{
    InitializeComponent();
}

private void groupBox1_Paint(object sender, PaintEventArgs e)
{
    // Here is where I want to use those variables: red_light1, yellow_light1…
}

public void timer_lights_status_Tick(object sender, EventArgs e)
{
    int red_light1, yellow_light1, green_light1,
        red_light2, yellow_light2, green_light2;

    red_light1    = Convert.ToInt32(comport.message(4, 8, 32));
    yellow_light1 = Convert.ToInt32(comport.message(4, 8, 33));
    green_light1  = Convert.ToInt32(comport.message(4, 8, 34));

    red_light2    = Convert.ToInt32(comport.message(4, 8, 35));
    yellow_light2 = Convert.ToInt32(comport.message(4, 8, 36));
    green_light2  = Convert.ToInt32(comport.message(4, 8, 37));
}

2 个答案:

答案 0 :(得分:1)

// Declare variables outside function scope. 
// This way, any function can access and modify these same variables.
int red_light1,yellow_light1,green_light1,
red_light2,yellow_light2,green_light2; 

public Main()
{
    InitializeComponent();
}

private void groupBox1_Paint(object sender, PaintEventArgs e)
{

  // Do something with variables: red_light1,yellow_light1... that you declared before
  // ex.:
  // red_light1 = 10;
  // CallAnotherFunction(red_light1);

}


public void timer_lights_status_Tick(object sender, EventArgs e)
{
    red_light1    = Convert.ToInt32(comport.message(4, 8, 32));
    yellow_light1 = Convert.ToInt32(comport.message(4, 8, 33));
    green_light1  = Convert.ToInt32(comport.message(4, 8, 34));

    red_light2    = Convert.ToInt32(comport.message(4, 8, 35));
    yellow_light2 = Convert.ToInt32(comport.message(4, 8, 36));
    green_light2  = Convert.ToInt32(comport.message(4, 8, 37));
}

答案 1 :(得分:0)

在Timer.Tick事件之外声明变量,以便您可以访问

当值更改时,刷新计时器事件本身的组合框

private void groupBox1_Paint(object sender, PaintEventArgs e)
{

  //Now those variables can be accessed here.

}

int red_light1,yellow_light1,green_light1,
       red_light2,yellow_light2,green_light2;

public void timer_lights_status_Tick(object sender, EventArgs e)
{
    red_light1    = Convert.ToInt32(comport.message(4, 8, 32));
    yellow_light1 = Convert.ToInt32(comport.message(4, 8, 33));
    green_light1  = Convert.ToInt32(comport.message(4, 8, 34));

    red_light2    = Convert.ToInt32(comport.message(4, 8, 35));
    yellow_light2 = Convert.ToInt32(comport.message(4, 8, 36));
    green_light2  = Convert.ToInt32(comport.message(4, 8, 37));

    groupBox1.Refresh();
}