您的代码缺少正确的事件初始化和使用。事件不能直接从其他类调用,但可以创建将为公共订阅者调用它的方法(在本例中是InvokeCalc方法)。这看起来像是你的工作:
public class Calculator
{
public event Calculate CalculateNow;
public delegate int Calculate(int x, int y);
public string InvokeCalc(int x, int y)
{
if(CalculateNow != null) return CalculateNow(x, y).ToString();
return null;
}
}
然后在winform中,您可以使用它:
namespace Project3
{
public partial class Form1 : Form
{
private Calculator calc;
public Form1()
{
InitializeComponent();
calc = new Calculator();
label1.Text = "";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
label1.Text = btn.Text;
int num1 = Int32.Parse(textBox1.Text);
int num2 = Int32.Parse(textBox2.Text);
// subscribes a handler to your event
calc.CalculateNow += (n1, n2) => { return n1 + n2; }
// method that invokes your event on Calculator class
int finalr = calc.InvokeCalc(num1, num2);
if (finalr != null)
{
label1.Text = "" + finalr;
}
else
{
label1.Text = "Error!";
}
}
}
}
附笔。
虽然这是一个示例,说明了如何使用事件,但不太可能必须这样使用事件。通常,应该使用事件来通知订阅者(其他类)事件已经发生。事件只能从类内部激发,这种封装提高了应用程序的完整性,否则
任何
类或结构可以触发此事件,并且很难找出哪个类实际调用了它以及在哪里。。。