usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceModernLanguageConstructs{classProgram{// Part 1 - Explicit declaration of a delegate //(helps a compiler ensure type safety)publicdelegatedoubledelegateConvertTemperature(doublesourceTemp);// A sample class to play withclassTemperatureConverterImp{// Part 2 - Will be attached to a delegate later in the codepublicdoubleConvertToFahrenheit(doublecelsius){return(celsius*9.0/5.0)+32.0;}// Part 3 - Will be attached to a delegate later in the codepublicdoubleConvertToCelsius(doublefahrenheit){return(fahrenheit-32.0)*5.0/9.0;}}staticvoidMain(string[]args){// Part 4 - Instantiate the main objectTemperatureConverterImpobj=newTemperatureConverterImp();// Part 5 - Intantiate delegate #1delegateConvertTemperaturedelConvertToFahrenheit=newdelegateConvertTemperature(obj.ConvertToFahrenheit);// Part 6 - Intantiate delegate #2delegateConvertTemperaturedelConvertToCelsius=newdelegateConvertTemperature(obj.ConvertToCelsius);// Use delegates to accomplish work// Part 7 - delegate #1doublecelsius=0.0;doublefahrenheit=delConvertToFahrenheit(celsius);stringmsg1=string.Format("Celsius = {0}, Fahrenheit = {1}",celsius,fahrenheit);Console.WriteLine(msg1);// Part 8 - delegate #2fahrenheit=212.0;celsius=delConvertToCelsius(fahrenheit);stringmsg2=string.Format("Celsius = {0}, Fahrenheit = {1}",celsius,fahrenheit);Console.WriteLine(msg2);}}}
Event example
Event是一种特殊类型的delegate,使用Event可以很方便的实现观察者模式。
12345678910111213141516171819202122
publicclassSampleEventArgs{publicSampleEventArgs(strings){Text=s;}publicStringText{get;privateset;}// readonly}publicclassPublisher{// Declare the delegate (if using non-generic pattern).publicdelegatevoidSampleEventHandler(objectsender,SampleEventArgse);// Declare the event.publiceventSampleEventHandlerSampleEvent;// Wrap the event in a protected virtual method// to enable derived classes to raise the event.protectedvirtualvoidRaiseSampleEvent(){// Raise the event by using the () operator.if(SampleEvent!=null)SampleEvent(this,newSampleEventArgs("Hello"));}}
Action example
Action是一种语法糖,它是一种不需要提前声明的delegate,使得delegate的使用更加方便,局限性就是不能定义返回值。(Func<> Delegates是一种可以定义返回值的语法糖)。
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceModernLanguageConstructs{classProgram{staticvoidMain(string[]args){// Part 1 - First action that takes an int and converts it to hexAction<int>displayHex=delegate(intintValue){Console.WriteLine(intValue.ToString("X"));};// Part 2 - Second action that takes a hex string and // converts it to an intAction<string>displayInteger=delegate(stringhexValue){Console.WriteLine(int.Parse(hexValue,System.Globalization.NumberStyles.HexNumber));};// Part 3 - exercise Action methodsdisplayHex(16);displayInteger("10");}}}