C#使用单个事件进行递增和递减

时间:2012-07-30 09:27:18

标签: c# events

我有一个递归函数和两个事件(Going_inComing_out)。

每次函数调用自身时,我都使用Going_in事件递增进度条,每次函数从递归返回时,我都会使用Coming_out递减进度条。

现在我必须将Going_inComing_out合并为一个事件。 我怎么能这样做?

提前致谢!

以下是代码的一部分。

Form1.cs的

   .....
   void ProgressBar_increment(object sender, EventArgs e)
    {
        progressBar1.Value++;

    }
    void ProgressBar_decrement(object sender, EventArgs e)
    {
        progressBar1.Value--;
    }
   public void button2_Click(object sender, EventArgs e)
    {
        initialize();
        label3.Visible = false;
        int wait_time = telltime();
        int number = reading();

        Facto mth;


        mth = new Facto(label3, wait_time, progressBar1);

        mth.Going_in += new EventHandler(ProgressBar_increment);
        mth.Coming_out += new EventHandler(ProgressBar_decrement);


        int result = mth.Factorial(number);

        string display = result.ToString();


        label3.Visible = true;

        label3.Text = display;
    }

Facto.cs

public event EventHandler Going_in;
public event EventHandler Coming_out;

........

public int Factorial(int number_to_calculate)
    {


        int Result;

        if (Going_in != null)
        {
            Going_in(this, new EventArgs());
        }


         System.Threading.Thread.Sleep(wait_time);
        if (number_to_calculate == 0)
        {
            if (Coming_out != null)
            {
                Coming_out(this, new EventArgs());
            }

            return 1;

        }
        else
       {
           Result = (number_to_calculate * Factorial(number_to_calculate - 1));
           if (label_for_output != null)
           {
               label_for_output.Visible = true;
               label_for_output.Text = Result.ToString();
               label_for_output.Update();
           }
           else 
               Console.WriteLine(Result);

       }


        if (Coming_out != null)
        {
            Coming_out(this, new EventArgs());
        }
        System.Threading.Thread.Sleep(wait_time);



        return Result;
    }

1 个答案:

答案 0 :(得分:4)

这就是EventArgs的用途。 在EventArgs对象中添加一些变量(或者为此目的创建自己的变量),从中可以确定是增加还是减少(enum可能?)

即。 (可能的伪代码警报)

if (Going_in != null)
{
   CustomEventArgs cea = new CustomEventArgs();
   cea.Type = Type.Decrement;
   Going_in(this, cea);
}

在您的活动中执行以下操作:

void ProgressBar_DoProgress(object sender, CustomEventArgs e)
 {
    if(e.Type == Type.Increment)
       progressBar1.Value++;

    if(e.Type == Type.Decrement)
       progressBar1.Value--;
 }