用慣了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();
}
}
}