c# - delegates events and null reference -
c# - delegates events and null reference -
in below code when programme executes workperformed
null
if (workperformed != null) { workperformed(hours, wt); }
can help me doing wrong learning delegates , events
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) { (int = 0; < 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) { homecoming string.format (" workhours {0} worktype {1} ", workhours, wtype); } } }
something has subscribe event in order become non-null:
delegatetestinstance.workperformed += new workperformedhandler(onworkperformed); ... void onworkperformed(...) { .... }
and remember unsubscribe event when don't want handle more, ensure resources cleared up:
delegatetestinstance.workperformed -= onworkperformed;
c# events delegates
Comments
Post a Comment