在下面的代码中,程序执行时WorkPerformed
始终为空
if (WorkPerformed != null)
{
WorkPerformed(hours, wt);
}
当我正在学习代表和活动时,任何人都可以帮助我做错事吗
namespace DelegateDemoApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DoSomethingElse();
}
public void DoSomethingElse()
{
DelegateTest dt = new DelegateTest();
dt.DoWork(10, WorkType.Permanent);
}
}
}
namespace DelegateDemoApp
{
public delegate void WorkPerformedHandler(int hours, WorkType workType);
public enum WorkType
{
Permanent = 1,
Contract = 2
}
public class DelegateTest
{
public event WorkPerformedHandler WorkPerformed;
public event EventHandler WorkCompletedEvent;
public void DoWork(int hours, WorkType wt)
{
for (int i = 0; i < hours; i++)
{
//raise Progress Event
OnWorkPerformedProgress(hours , wt);
}
}
protected virtual void OnWorkPerformedProgress(int hours, WorkType wt)
{
if (WorkPerformed != null)
{
WorkPerformed(hours, wt);
}
}
public DelegateTest()
{
}
public void Supervisor_WorkPerformed(int shiftHours, WorkType WType)
{
string.Format(" WorkHours {0} WorkType {1} ", shiftHours, WType);
}
public string Manager_WorkPerformed(int workHours, WorkType WType)
{
return string.Format (" WorkHours {0} WorkType {1} ", workHours, WType);
}
}
}
答案 0 :(得分:3)
必须订阅该事件才能使其变为非空:
delegateTestInstance.WorkPerformed += new WorkPerformedHandler(OnWorkPerformed);
...
void OnWorkPerformed(...)
{
....
}
当您不想再处理时,请务必取消订阅该活动,以确保清理资源:
delegateTestInstance.WorkPerformed -= OnWorkPerformed;