SlideShare uma empresa Scribd logo
1 de 12
The Simplest Possible Delegate Example
namespace SimpleDelegate
{
public delegate int BinaryOp(int x, int y);
public class SimpleMath
{
public static int Add(int x, int y)
{ return x + y; }
public static int Subtract(int x, int y)
{ return x – y; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Simple Delegate Example *****n");
// Create a BinaryOp object that
// "points to" SimpleMath.Add().
BinaryOp b = new BinaryOp(SimpleMath.Add);
// Invoke Add() method using delegate.
Console.WriteLine("10 + 10 is {0}", b(10, 10));
BinaryOp b2 = new BinaryOp(SimpleMath. Subtract);
Console.WriteLine("10 - 10 is {0}", b2(10, 10));
Console.ReadLine();
}
}
}
Investigating a Delegate Object
• by creating a helper function named DisplayDelegateInfo().
• This method will print out names of the methods maintained by the incoming
System.Delegate derived type as well as the name of the class defining the method.
• To do so, we will iterate over the System.Delegate array returned by GetInvocationList(),
invoking each object’s Target and Method properties:
static void DisplayDelegateInfo(Delegate delObj)
{
// Print the names of each member in the
// delegate's invocation list.
foreach (Delegate d in delObj.GetInvocationList())
{
Console.WriteLine("Method Name: {0}", d.Method);
Console.WriteLine("Type Name: {0}", d.Target);
}
}
Car Type with Delegates
• Define the AboutToBlow and Exploded delegates.
• Declare member variables of each delegate type in the Car class.
• Create helper functions on the Car that allow the caller to specify the
methods maintained by the delegate member variables.
• Update the Accelerate() method to invoke the delegate’s invocation
list under the correct circumstances.
public class Car
{
// Define the delegate types.
public delegate void AboutToBlow(string msg);
public delegate void Exploded (string msg);
// Define member variables of each delegate type.
private AboutToBlow almostDeadList;
private Exploded explodedList;
// Add members to the invocation lists using helper methods.
public void OnAboutToBlow(AboutToBlow clientMethod)
{ almostDeadList = clientMethod; }
public void OnExploded(Exploded clientMethod)
{ explodedList = clientMethod; }
...
}
public void Accelerate(int delta)
{
if (carIsDead){
if (explodedList != null)
explodedList("Sorry, this car is dead...");}
else{
currSpeed += delta;
if (10 == maxSpeed - currSpeed
&& almostDeadList != null){
almostDeadList("Careful buddy! Gonna blow!");}
if (currSpeed >= maxSpeed)
carIsDead = true;
else
Console.WriteLine("->CurrSpeed = {0}", currSpeed);
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Delegates as event enablers *****");
// Make a car as usual.
Car c1 = new Car("SlugBug", 100, 10);
// Register event handlers with Car type.
c1.OnAboutToBlow(new Car.AboutToBlow(CarAboutToBlow));
c1.OnExploded(new Car.Exploded(CarExploded));
Console.WriteLine("n***** Speeding up *****");
for (int i = 0; i < 6; i++)
c1.Accelerate(20);
Console.ReadLine();
}
// The Car will call these methods.
public static void CarAboutToBlow(string msg)
{ Console.WriteLine(msg); }
public static void CarExploded(string msg)
{ Console.WriteLine(msg); }
}
A More Elaborate Delegate Example
// Updated Car class.
public class Car
{
…
// Are we in need of a wash? Need to rotate tires?
private bool isDirty;
private bool shouldRotate;
// Extra params to set bools.
public Car(string name, int max, int curr,
bool washCar, bool rotateTires){
...
isDirty = washCar;
shouldRotate = rotateTires;}
public bool Dirty{
get{ return isDirty; }
set{ isDirty = value; }}
}
public bool Rotate
{
get{ return shouldRotate; }
set{ shouldRotate = value; }
}
}
Now, also assume the Car type nests a new delegate, CarDelegate:
// Car defines yet another delegate.
public class Car
{
...
// Can call any method taking a Car as
// a parameter and returning nothing.
public delegate void CarDelegate(Car c);
...
}
Delegates As Parameters
Using System.Collections;
...
public class Garage
{
...
// This method takes a Car.CarDelegate as a parameter.
public void ProcessCars(Car.CarDelegate proc)
{
// Where are we forwarding the call?
Console.WriteLine("***** Calling: {0} *****",
proc.Method);
// Are we calling an instance method or a static method?
if(proc.Target != null)
Console.WriteLine("—>Target: {0} ", proc.Target);
else
Console.WriteLine("—>Target is a static method");
// Call the method "pointed to," passing in each car.
foreach (Car c in theCars)
{
Console.WriteLine("n-> Processing a Car");
proc(c);
}
}
}

Mais conteúdo relacionado

Semelhante a The C# programming laguage delegates notes Delegates.pptx

TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsAlfonso Peletier
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersBartosz Kosarzycki
 
I need this code, to show ALL inventory items, then with the remove .pdf
I need this code, to show ALL inventory items, then with the remove .pdfI need this code, to show ALL inventory items, then with the remove .pdf
I need this code, to show ALL inventory items, then with the remove .pdfaggarwalshoppe14
 
I need to do the followingAdd a new item to the inventory m.pdf
I need to do the followingAdd a new item to the inventory m.pdfI need to do the followingAdd a new item to the inventory m.pdf
I need to do the followingAdd a new item to the inventory m.pdfadianantsolutions
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016STX Next
 
In C#, visual studio, I want no more text boxes added, I have button.pdf
In C#, visual studio, I want no more text boxes added, I have button.pdfIn C#, visual studio, I want no more text boxes added, I have button.pdf
In C#, visual studio, I want no more text boxes added, I have button.pdfaggarwalenterprisesf
 
2014 computer science_question_paper
2014 computer science_question_paper2014 computer science_question_paper
2014 computer science_question_papervandna123
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesAndrey Karpov
 
Cs pritical file
Cs pritical fileCs pritical file
Cs pritical fileMitul Patel
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Sumant Tambe
 
Does testability imply good design - Andrzej Jóźwiak - TomTom Dev Day 2022
Does testability imply good design - Andrzej Jóźwiak - TomTom Dev Day 2022Does testability imply good design - Andrzej Jóźwiak - TomTom Dev Day 2022
Does testability imply good design - Andrzej Jóźwiak - TomTom Dev Day 2022Andrzej Jóźwiak
 
12th CBSE Practical File
12th CBSE Practical File12th CBSE Practical File
12th CBSE Practical FileAshwin Francis
 

Semelhante a The C# programming laguage delegates notes Delegates.pptx (20)

TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic LabsTypeScript - All you ever wanted to know - Tech Talk by Epic Labs
TypeScript - All you ever wanted to know - Tech Talk by Epic Labs
 
ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
 
C++ programs
C++ programsC++ programs
C++ programs
 
Day 1
Day 1Day 1
Day 1
 
I need this code, to show ALL inventory items, then with the remove .pdf
I need this code, to show ALL inventory items, then with the remove .pdfI need this code, to show ALL inventory items, then with the remove .pdf
I need this code, to show ALL inventory items, then with the remove .pdf
 
I need to do the followingAdd a new item to the inventory m.pdf
I need to do the followingAdd a new item to the inventory m.pdfI need to do the followingAdd a new item to the inventory m.pdf
I need to do the followingAdd a new item to the inventory m.pdf
 
Kotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projects
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
 
C lab programs
C lab programsC lab programs
C lab programs
 
C lab programs
C lab programsC lab programs
C lab programs
 
In C#, visual studio, I want no more text boxes added, I have button.pdf
In C#, visual studio, I want no more text boxes added, I have button.pdfIn C#, visual studio, I want no more text boxes added, I have button.pdf
In C#, visual studio, I want no more text boxes added, I have button.pdf
 
2014 computer science_question_paper
2014 computer science_question_paper2014 computer science_question_paper
2014 computer science_question_paper
 
Best Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' MistakesBest Bugs from Games: Fellow Programmers' Mistakes
Best Bugs from Games: Fellow Programmers' Mistakes
 
Cs pritical file
Cs pritical fileCs pritical file
Cs pritical file
 
Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)Fun with Lambdas: C++14 Style (part 1)
Fun with Lambdas: C++14 Style (part 1)
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
 
Final DAA_prints.pdf
Final DAA_prints.pdfFinal DAA_prints.pdf
Final DAA_prints.pdf
 
7720
77207720
7720
 
Does testability imply good design - Andrzej Jóźwiak - TomTom Dev Day 2022
Does testability imply good design - Andrzej Jóźwiak - TomTom Dev Day 2022Does testability imply good design - Andrzej Jóźwiak - TomTom Dev Day 2022
Does testability imply good design - Andrzej Jóźwiak - TomTom Dev Day 2022
 
12th CBSE Practical File
12th CBSE Practical File12th CBSE Practical File
12th CBSE Practical File
 

Último

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...ranjana rawat
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 

Último (20)

(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
(RIA) Call Girls Bhosari ( 7001035870 ) HI-Fi Pune Escorts Service
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
(TARA) Talegaon Dabhade Call Girls Just Call 7001035870 [ Cash on Delivery ] ...
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 

The C# programming laguage delegates notes Delegates.pptx

  • 1. The Simplest Possible Delegate Example namespace SimpleDelegate { public delegate int BinaryOp(int x, int y); public class SimpleMath { public static int Add(int x, int y) { return x + y; } public static int Subtract(int x, int y) { return x – y; } }
  • 2. class Program { static void Main(string[] args) { Console.WriteLine("***** Simple Delegate Example *****n"); // Create a BinaryOp object that // "points to" SimpleMath.Add(). BinaryOp b = new BinaryOp(SimpleMath.Add); // Invoke Add() method using delegate. Console.WriteLine("10 + 10 is {0}", b(10, 10)); BinaryOp b2 = new BinaryOp(SimpleMath. Subtract); Console.WriteLine("10 - 10 is {0}", b2(10, 10)); Console.ReadLine(); } } }
  • 3. Investigating a Delegate Object • by creating a helper function named DisplayDelegateInfo(). • This method will print out names of the methods maintained by the incoming System.Delegate derived type as well as the name of the class defining the method. • To do so, we will iterate over the System.Delegate array returned by GetInvocationList(), invoking each object’s Target and Method properties: static void DisplayDelegateInfo(Delegate delObj) { // Print the names of each member in the // delegate's invocation list. foreach (Delegate d in delObj.GetInvocationList()) { Console.WriteLine("Method Name: {0}", d.Method); Console.WriteLine("Type Name: {0}", d.Target); } }
  • 4. Car Type with Delegates • Define the AboutToBlow and Exploded delegates. • Declare member variables of each delegate type in the Car class. • Create helper functions on the Car that allow the caller to specify the methods maintained by the delegate member variables. • Update the Accelerate() method to invoke the delegate’s invocation list under the correct circumstances.
  • 5. public class Car { // Define the delegate types. public delegate void AboutToBlow(string msg); public delegate void Exploded (string msg); // Define member variables of each delegate type. private AboutToBlow almostDeadList; private Exploded explodedList; // Add members to the invocation lists using helper methods. public void OnAboutToBlow(AboutToBlow clientMethod) { almostDeadList = clientMethod; } public void OnExploded(Exploded clientMethod) { explodedList = clientMethod; } ... }
  • 6. public void Accelerate(int delta) { if (carIsDead){ if (explodedList != null) explodedList("Sorry, this car is dead...");} else{ currSpeed += delta; if (10 == maxSpeed - currSpeed && almostDeadList != null){ almostDeadList("Careful buddy! Gonna blow!");} if (currSpeed >= maxSpeed) carIsDead = true; else Console.WriteLine("->CurrSpeed = {0}", currSpeed); } }
  • 7. class Program { static void Main(string[] args) { Console.WriteLine("***** Delegates as event enablers *****"); // Make a car as usual. Car c1 = new Car("SlugBug", 100, 10); // Register event handlers with Car type. c1.OnAboutToBlow(new Car.AboutToBlow(CarAboutToBlow)); c1.OnExploded(new Car.Exploded(CarExploded)); Console.WriteLine("n***** Speeding up *****"); for (int i = 0; i < 6; i++) c1.Accelerate(20); Console.ReadLine(); }
  • 8. // The Car will call these methods. public static void CarAboutToBlow(string msg) { Console.WriteLine(msg); } public static void CarExploded(string msg) { Console.WriteLine(msg); } }
  • 9. A More Elaborate Delegate Example // Updated Car class. public class Car { … // Are we in need of a wash? Need to rotate tires? private bool isDirty; private bool shouldRotate; // Extra params to set bools. public Car(string name, int max, int curr, bool washCar, bool rotateTires){ ... isDirty = washCar; shouldRotate = rotateTires;} public bool Dirty{ get{ return isDirty; } set{ isDirty = value; }}
  • 10. } public bool Rotate { get{ return shouldRotate; } set{ shouldRotate = value; } } } Now, also assume the Car type nests a new delegate, CarDelegate: // Car defines yet another delegate. public class Car { ... // Can call any method taking a Car as // a parameter and returning nothing. public delegate void CarDelegate(Car c); ... }
  • 11. Delegates As Parameters Using System.Collections; ... public class Garage { ... // This method takes a Car.CarDelegate as a parameter. public void ProcessCars(Car.CarDelegate proc) { // Where are we forwarding the call? Console.WriteLine("***** Calling: {0} *****", proc.Method); // Are we calling an instance method or a static method? if(proc.Target != null) Console.WriteLine("—>Target: {0} ", proc.Target); else Console.WriteLine("—>Target is a static method");
  • 12. // Call the method "pointed to," passing in each car. foreach (Car c in theCars) { Console.WriteLine("n-> Processing a Car"); proc(c); } } }