用惯了qt的信号和槽,转到c#觉得很别扭。微软擅长把简单的东西设计的很复杂。不过吐吐也就习惯了。
下面的例子是一个公司里面有职员和hr,职员要加薪,发射信号给hr和公司的例子。同时用到了平行传递和向上传递信号。
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace Delegate_And_Event
{
public delegate void SalaryComputeEventHander(object sender, MyEventArgs e);
public class Company
{
public Employee emp1;
public HumanResource hr1;
public Company()
{
emp1 = new Employee();
hr1 = new HumanResource();
emp1.SalaryPromoted += new SalaryComputeEventHander(hr1.SalaryHandler); //将具 体事件处理函数注册到事件中
emp1.SalaryPromoted += new SalaryComputeEventHander(getEmployeeSlot);
}
public void getEmployeeSlot(object sender, MyEventArgs e)
{
Console.WriteLine("company respone:negtive");
}
}
public class Employee
{
public event SalaryComputeEventHander SalaryPromoted;
public void OnSalaryCompute(MyEventArgs e) //触发事件的函数
{
if (SalaryPromoted != null)
{
Console.WriteLine("Employee ask for a promotion to 15000$");
SalaryPromoted(this, e);
}
}
}
public class HumanResource
{
//具体的事件处理函数
public void SalaryHandler(object sender, MyEventArgs e)
{
Console.WriteLine("HR response:Salary is {0},already high enough,will not be promoted", e._salary-3000);
}
}
public class MyEventArgs : EventArgs
{
public readonly double _salary;
public MyEventArgs(double salary)
{
this._salary = salary;
}
}
class Program
{
static void Main(string[] args)
{
Company comp1 = new Company();
MyEventArgs e = new MyEventArgs(15000);
comp1.emp1.OnSalaryCompute(e);
Console.ReadKey();
}
}
}