我制作了一个计算数字阶乘的 Windows 窗体应用程序。一切都很好,但现在我必须使用事件来做到这一点。事件的概念对我来说是新的,过去三天我一直试图让它发挥作用,但无济于事。
我有表格:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
... some function declarations...
//public event EventHandler ProgressBarChanged;
public int OnProgressBarChanged()
{
progressBar1.Value++;
return progressBar1.Value;
}
public void button2_Click(object sender, EventArgs e)
{
initialize();
label3.Visible = false;
int wait_time = telltime();
int number = reading();
Facto mth;
if (checkBox1.Checked && checkBox2.Checked)
{
mth = new Facto(label3, wait_time, progressBar1);
}
else if(checkBox1.Checked==false && checkBox2.Checked)
{
mth = new Facto(label3,wait_time);
}
else if (checkBox1.Checked && checkBox2.Checked == false)
{
checkBox1.Checked = false;
mth = new Facto();
}
else
{
mth = new Facto();
}
mth.Subs += new Eventhandler(OnProgressBarChanged); // Error. I don't understand why
int result = mth.Factorial(number);
string display = result.ToString();
label3.Visible = true;
label3.Text = display;
}
和Facto
班级:
public class Facto
{
public event EventHandler Subs;
System.Windows.Forms.Label label_for_output;
int wait_time;
System.Windows.Forms.ProgressBar bar;
public Facto()
{
}
public Facto(System.Windows.Forms.Label l, int time)
{
label_for_output = l;
wait_time = time;
}
public int Factorial(int number_to_calculate)
{
int Result;
if (Subs != null)
{
Subs(this, new EventArgs());
}
System.Threading.Thread.Sleep(wait_time);
if (number_to_calculate == 0)
{
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);
}
System.Threading.Thread.Sleep(wait_time);
return Result;
}
}
}
该事件应在递归函数调用自身时触发。当事件被触发时,Form1 中的progressbar1.value 应该增加1(当它从递归返回时它也应该减少,但我更感兴趣的是让它首先工作)。
我怎样才能解决这个问题?
我真的很困惑,我只能找到显示消息或解释得很糟糕的示例。