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

ADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developers
Bartosz 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 .pdf
aggarwalshoppe14
 
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
adianantsolutions
 
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
aggarwalenterprisesf
 

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

scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
HenryBriggs2
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
Epec Engineered Technologies
 
Cybercrimes in the Darknet and Their Detections: A Comprehensive Analysis and...
Cybercrimes in the Darknet and Their Detections: A Comprehensive Analysis and...Cybercrimes in the Darknet and Their Detections: A Comprehensive Analysis and...
Cybercrimes in the Darknet and Their Detections: A Comprehensive Analysis and...
dannyijwest
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
Kamal Acharya
 

Último (20)

NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
scipt v1.pptxcxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx...
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth Reinforcement
 
Introduction to Geographic Information Systems
Introduction to Geographic Information SystemsIntroduction to Geographic Information Systems
Introduction to Geographic Information Systems
 
Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)Introduction to Artificial Intelligence ( AI)
Introduction to Artificial Intelligence ( AI)
 
8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
Databricks Generative AI Fundamentals .pdf
Databricks Generative AI Fundamentals  .pdfDatabricks Generative AI Fundamentals  .pdf
Databricks Generative AI Fundamentals .pdf
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
 
Signal Processing and Linear System Analysis
Signal Processing and Linear System AnalysisSignal Processing and Linear System Analysis
Signal Processing and Linear System Analysis
 
Adsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) pptAdsorption (mass transfer operations 2) ppt
Adsorption (mass transfer operations 2) ppt
 
Danikor Product Catalog- Screw Feeder.pdf
Danikor Product Catalog- Screw Feeder.pdfDanikor Product Catalog- Screw Feeder.pdf
Danikor Product Catalog- Screw Feeder.pdf
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Cybercrimes in the Darknet and Their Detections: A Comprehensive Analysis and...
Cybercrimes in the Darknet and Their Detections: A Comprehensive Analysis and...Cybercrimes in the Darknet and Their Detections: A Comprehensive Analysis and...
Cybercrimes in the Darknet and Their Detections: A Comprehensive Analysis and...
 
Path loss model, OKUMURA Model, Hata Model
Path loss model, OKUMURA Model, Hata ModelPath loss model, OKUMURA Model, Hata Model
Path loss model, OKUMURA Model, Hata Model
 
Augmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptxAugmented Reality (AR) with Augin Software.pptx
Augmented Reality (AR) with Augin Software.pptx
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 

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); } } }