Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 3260.  C++ Function Pointers  C# Method References  Groundwork for Lambda Functions.

Similar presentations


Presentation on theme: "CS 3260.  C++ Function Pointers  C# Method References  Groundwork for Lambda Functions."— Presentation transcript:

1 CS 3260

2  C++ Function Pointers  C# Method References  Groundwork for Lambda Functions

3  int (*)(int,double) fPtr;

4  A delegate type represents references to methods with a particular parameter list and return type. Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters.  Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters.

5  Delegates provide the groundwork for Lambda Functions.  Lambda Functions will be discussed in a later lesson.

6  Reference Type  Delegate Type Declaration  delegate void MyDelegate(int ival, double dval);  Delegate Variable Declaration & Assignment  MyDelegate mdel = new MyDelegate(MyMethod); or  MyDelegate mdel = MyMethod; or  mdel += TestMethod;  Method Declaration  void MyMethod(int iv,double dv){ … }  Void TestMethod(int j,double k){…}  Method Call via the Delegate  mdel(100,5.5);  Type-Safe  Can have generic parameters

7 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 7  A delegate-declaration is a type-declaration (§9.5) that declares a new delegate type.§9.5  delegate-declaration: attributes opt delegate-modifiers opt delegate return-type identifier(formal- parameter-list opt ) ; delegate-modifiers: delegate-modifier delegate-modifiers delegate-modifier delegate-modifier: new public protected internal private  Example public delegate void D(int x);

8 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 8  A delegate declaration defines a new type  Delegates are similar to function pointers  C++ function pointer -> int (*)(int,double);  Delegates are type-safe  Delegates are object-oriented  A form of polymorphism  Delegate types are derived from System.MulticastDelegate

9 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 9 Exposed Command VariableCommand object instance Command executor Command Class Execute() Command issuer Command Subclass Execute() Knows when the event happens but doesn’t know what to do about it Knows what to do when an event happens but doesn’t know when

10 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 10 Delegate Host Class (Publisher) Exposed Delegate Knows when the event happens but doesn’t know what to do about it Delegate User Class (Subscriber) Knows what to do when an event happens but doesn’t know when Subscribing Method AKA: The Observer Pattern or.NET Event Model

11 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 11  When you want different things to happen when an event occurs  GUI events ->  this.BtnExit.Click += new System.EventHandler(this.BtnExit_Click);  private void BtnExit_Click(object sender, EventArgs e) { Close(); }  Threading situations  Callbacks  Command Pattern  To keep your interface clean  Looser coupling

12 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 12  three steps: 1. Delegate Declaration 2. Delegate Instantiation 3. Function Declaration 4. Delegate Invocation (call)

13 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 13 namespace some_namespace { delegate void MyDelegate(int x, int y); //namespace scope class MyClass { public delegate int AnotherDelegate(object o, int y); //class scope } Delegate Name (Type)

14 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 14 delegate void MyDelegate(int x, int y); //namespace scope class MyClass { private MyDelegate myDelegate = new MyDelegate( SomeFun ); public static void SomeFun(int dx, int dy) { //method body } Invocation Method name (no params or parens)

15 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 15 class MyClass { private MyDelegate myDelegate; //class scope public MyDelegate MyDelegate { set { this.myDelegate = value; } } class MainClass { [STAThread] static void Main() { MyClass mc = new MyClass(); mc.MyDelegate = new MyDelegate( MainClassMethod ); } private static void MainClassMethod(int x, int y) { } } Delegate Variable (null) Passed in and assigned in the constructor

16 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 16 class MyClass { private MyDelegate myDelegate; public MyDelegate MyDelegate { set { this.MyDelegate = value; } } class MainClass { [STAThread] static void Main() { MainClass mainClass = new MainClass(); MyClass mc = new MyClass(); mc.MyDelegate = new MyDelegate( mainClass.MainClassMethod ); } private void MainClassMethod(int x, int y) { } } Method attached to an instance

17 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 17  A Method is compatible with a Delegate if and only if:  They have the same type and number of parameters  They have the same return type  Name?

18 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 18 class MyClass { private MyDelegate myDelegate; public MyClass(MyDelegate myDelegate) { this.MyDelegate = myDelegate; } private void WorkerMethod() { int x = 500, y = 1450; if(myDelegate != null) myDelegate(x, y); } Attempting to invoke a delegate instance whose value is null results in an exception of type System.NullReferenceException.

19 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 19  Delegate is really an array of function pointers  Now when Invoked, mc.MyDelegate will execute all three Methods  Notice that you don’t have to instantiate the delegate before using +=  The compiler does it for you when calling += mc.MyDelegate += new MyDelegate( mc.Method1 ); mc.MyDelegate += new MyDelegate( mc.Method2 ); mc.MyDelegate = mc.MyDelegate + new MyDelegate( mc.Method3 );

20 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 20  Methods are executed in the order they are added  Add methods with + or +=  Remove methods with - or -=  Attempting to remove a method that does not exist is not an error  Return value is whatever the last method returns  A delegate may be present in the invocation list more than once  The delegate is executed as many times as it appears (in the appropriate order)  Removing a delegate that is present more than once removes only the last occurrence

21 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 21 mc.MyDelegate = new MyDelegate( mc.Method1 ); mc.MyDelegate += new MyDelegate( mc.Method2 ); mc.MyDelegate = mc.MyDelegate + new MyDelegate( mc.Method3 ); // The call to: mc.MyDelegate(0, 0); // executes: // mc.Method1 // mc.Method2 // mc.Method3 (See Delegates Demo)

22 public delegate int TestDel(int iv); //delegate declaration TestDel delref = new TestDel(FooBar);//delegate initialization delref += FooBar;//Short form delref += Method0;//chaining a delegate delref -= FooBar;//unchaining a delegate delref = delegate (int x){ return x + 100; } //anynomous method static public int FooBar(int ival){ … return i; }//Method static public int Method0(int x){ … return x; } //Other method Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 22

23 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 23  abstract  Special  Only the system and compiler can inherit from System.Delegate  Members:  Method  Returns A MethodInfo object  Target  The ‘this’ pointer belonging to the method  null if the method was static  operator == and operator !=

24 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 24  Target  Method  operator== and operator !=  _prev  Linked list of System.Delegate objects  GetInvocationList()  Returns the Invocation List as a Delegate[]

25 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 25  Exposing a delegate might be bad if:  You don’t want others to invoke your delegate  You have assigned to the delegate internally  Enter the event keyword...

26  delegate T Gdelegate (T tval,K kval);  Func<> Func  Func  Action<> void Action  void Action

27 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 27  Events are “safe” delegates  But they are delegates  Restricts use of the delegate (event) to the target of a += or -= operation  No assignment  No invocation  No access of delegate members (like GetInvocation List)  Allow for their own Exposure  Event Accessors

28 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 28 public delegate void FireThisEvent(); class MyEventWrapper { private event FireThisEvent fireThisEvent; public void OnSomethingHappens() { if(fireThisEvent != null) fireThisEvent(); } public event FireThisEvent FireThisEvent { add { fireThisEvent += value; } remove { fireThisEvent -= value; } } add and remove keywords (See Event Demo)

29 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 29  Exceptions thrown from a delegate:  Are thrown to the calling context  All subsequent delegates in the Invocation List are ignored

30 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 30  ThreadStart  TimerCallback  ASyncCallback  EventHandler  KeyPressEventHandler  KeyEventHandler  etc.

31 Copyright © 2005-2008 by Dennis A. Fairclough all rights reserved. 31  ??


Download ppt "CS 3260.  C++ Function Pointers  C# Method References  Groundwork for Lambda Functions."

Similar presentations


Ads by Google