c# - Can I use something else instead of "this" in this code? -
using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; namespace event_training { class publisher { public event eventhandler x; public void raise() { x(this, null); } } class subscriber { public void method1(object o, eventargs e) { console.writeline("metod1 called"); } public void method2(object o, eventargs e) { console.writeline("metod2 called"); } } class program { static void main(string[] args) { publisher p = new publisher(); subscriber s = new subscriber(); p.x += s.method1; p.x += s.method2; p.raise(); } } }
having hard time understrand "this" keyword. refer "x(this, null);" in here? can use else instead of "this"?
why need pass instance of publisher
? assume have several publishers , 1 subscriber:
publisher p1 = new publisher() { name = "bob" }; publisher p2 = new publisher() { name = "joe" }; subscriber s = new subscriber();
you subscribe x
event of both publishers:
p1.x += s.method1; p2.x += s.method1;
now question - how know publisher raised event in event handle?
public void method1(object o, eventargs e) { console.writeline("metod1 called"); }
that's why default eventhandler
delegate has 2 parameters. first 1 called sender
instead of o
. able check sender
, understand publisher raised event. assume publisher
has name
property:
class publisher { public event eventhandler x; public string name { get; set; } public void raise() { eventhandler x = this.x; if (x != null) x(this, eventargs.empty); } }
now in event handler can name of publisher, because have passed publisher instance (this
) handler:
public void method1(object sender, eventargs e) { publisher publisher = (publisher)sender; console.writeline(publisher.name + " raised event x"); }
if don't need pass event args , instance of object raised event, can use other type of delegate event. e.g. action
delegate not have parameters.
class publisher { public event action x; public void raise() { action x = this.x; if (x != null) x(); // no parameters } }
and handler like:
public void method1() { console.writeline("metod1 called"); }
Comments
Post a Comment