13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Delegates37A COMPLETE EXAMPLE AND SOME MOTIVATIONIt’s easiest to see all this <strong>in</strong> action <strong>in</strong> a complete example—f<strong>in</strong>ally, someth<strong>in</strong>g we canactually run! As there are lots of bits and pieces go<strong>in</strong>g on, I’ve <strong>in</strong>cluded the wholesource code this time rather than us<strong>in</strong>g snippets. There’s noth<strong>in</strong>g m<strong>in</strong>d-blow<strong>in</strong>g <strong>in</strong> list<strong>in</strong>g2.1, so don’t expect to be amazed—it’s just useful to have concrete code to discuss.List<strong>in</strong>g 2.1Us<strong>in</strong>g delegates <strong>in</strong> a variety of simple waysus<strong>in</strong>g System;delegate void Str<strong>in</strong>gProcessor(str<strong>in</strong>g <strong>in</strong>put);BDeclaresdelegate typeclass Person{}str<strong>in</strong>g name;public Person(str<strong>in</strong>g name){this.name = name;}public void Say(str<strong>in</strong>g message){Console.WriteL<strong>in</strong>e ("{0} says: {1}", name, message);}CDeclares compatible<strong>in</strong>stance methodclass Background{public static void Note(str<strong>in</strong>g note){Console.WriteL<strong>in</strong>e ("({0})", note);}DDeclares compatiblestatic method}class SimpleDelegateUse{static void Ma<strong>in</strong>(){Person jon = new Person("Jon");Person tom = new Person("Tom");Str<strong>in</strong>gProcessor jonsVoice, tomsVoice, background;jonsVoice = new Str<strong>in</strong>gProcessor(jon.Say);tomsVoice = new Str<strong>in</strong>gProcessor(tom.Say);background = new Str<strong>in</strong>gProcessor(Background.Note);E Createsthreedelegate<strong>in</strong>stances}}jonsVoice("Hello, son.");tomsVoice.Invoke("Hello, Daddy!");background("An airplane flies past.");Invokes delegate<strong>in</strong>stancesTo start with, we declare the delegate type B. Next, we create two methods (Cand D) that are both compatible with the delegate type. We’ve got one <strong>in</strong>stancemethod (Person.Say) and one static method (Background.Note) so that we can seeFLicensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!