1 / 23

C# part II

C# part II. Delegates and Events Dynamic functions Extension methods Closures. Events and Delegates. C# Terminology Event: a field representing a multi-set of delegates Defined with event keyword Operations Add delegate using += operator

Télécharger la présentation

C# part II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C# part II • Delegates and Events • Dynamic functions • Extension methods • Closures

  2. Events and Delegates • C# Terminology • Event: a field representing a multi-set of delegates • Defined with event keyword • Operations • Add delegate using += operator += has default implementation, but user can provide his own add. • Remove delegate using -= operator -= has a default implementation, but user can provide his own del. • Call all delegates in the multi-set • Delegate: type safe function pointer • defined with delegate keyword • part of the class hierarchy • Classical Example: when a button is pressed, listeners should be notified with "callback functions" • Our Example:royal social conduct • If King is happy: notify all men in the kingdom • If King is ill: notify noblemen only.

  3. King, Nobleman and Citizens • Name: every man has a name • Title: every man has a title, based on his status and name • Realized by method ToString() • Service: every man can be set to service any number of kings. • Method service(King k) in class Man Kingdomnamespace Manabstract Lifestatic Notify delegate Stateenum Citizensealed Noblemanconcrete Kingconcrete

  4. Delegate Notify • Type Definition: pointer to a function (to be called when a king changes his state) namespace Kingdom { delegateObject Notify(King k); … } • Simple (uninteresting) use:void foo(King k) { Notify bar; // A variable of typeNotify bar = new Notify(FunctionDescriptor); … Object o = bar(k); // InvokeFunctionDescriptor } • More interesting use:class Foo {event Notify baz; // A multi-set of variables of typeNotifypublicvoid foo(King k) { baz += new Notify(FunctionDescriptor); … Object o = baz(k); // InvokeFunctionDescriptor } } Notify delegate

  5. Class King and Enum State Stateenum namespace Kingdom {… enum State {happy, ill }; class King : Man {public State state; public King(String name):base(name){state = State.ill;} sealedoverridepublic String ToString() { return "His Majesty, King " + Name; } // public multi-sets of those interested in the King's being. public event Notify when_ill, when_happy; publicObjectbecome_ill() { // returns last listener return value state = State.ill;return when_ill != null ? when_ill(this) : null; } publicObjectbecome_happy(){ // returns last listener return valuestate = State.happy; return when_happy != null ? when_happy(this) : null; } } … } Kingconcrete

  6. Class Man Manabstract namespace Kingdom { abstractclass Man { protectedreadonly String Name; public Man(String name) { Name = name; } abstractoverridepublic String ToString(); // Every man is happy when a King he serves is happy.virtualpublicvoid serve(King k) { k.when_happy += new Notify(happy); } publicMan happy(Objectother) { Console.WriteLine(this + " is happy to hear that " + other +" is happy."); returnthis; } { ... }

  7. Delegates and Events • Delegate type definition: pointer to a function (to be called when a king changes his state) namespace Kingdom { delegateObject Notify(King k); … } • Event definition:a field with a multi-set of delegates namespace Kingdom {class King: Man {public event Notify when_ill, when_happy; … } It is possible (but not very useful) to define a field which contains a single delegate. class KING: King {public Notify queen_listner;}

  8. Registration of an Actual Delegate • Actual Delegate:a function for notification namespace Kingdom {…abstract class Man {public Manhappy(Object other) { Console.WriteLine(this + " is happy to hear that " + other + " is happy.");returnthis; } }… }… • Register a delegate:with += operator namespace Kingdom {abstractclass Man {virtual public void serve(King k) { k.when_happy += new Notify(happy); } } }

  9. Classes Citizen and Nobleman namespace Kingdom {…sealed class Citizen: Man { public Citizen(String name) : base(name) { } overridepublic String ToString() { return "Citizen " + Name;} } class Nobleman: Man { public Nobleman(String name) : base(name) { } overridepublic String ToString() { return "Nobleman " + Name;} publicNobleman ill(Objectother) { Console.WriteLine(this + " is sorry to hear that " + other+" is ill.");returnthis; } override public void serve(King k) { base.serve(k); k.when_ill += new Notify(ill); } }{ Citizensealed Noblemanconcrete

  10. Main Application Al Bob Richard George Virgil static class Life { staticvoid Main() { King R = new King("Richard"), G = new King("George"); Citizen a = new Citizen("Al"), b = new Citizen("Bob"); Nobleman v = new Nobleman("Virgil"); a.serve(R); b.serve(R);b.serve(G); v.serve(R); G.serve(R); R.become_ill(); R.become_happy(); Console.WriteLine("----"); G.become_ill(); G.become_happy(); Console.WriteLine("----"); } } Lifestatic

  11. Output Al Bob Richard George Virgil NoblemenVirgil is sorry to hear that His Majesty, King Richard is ill. Citizen Al is happy to hear that His Majesty, King Richard is happy. Citizen Bob is happy to hear that His Majesty, King Richard is happy. NoblemenVirgil is happy to hear that His Majesty, King Richard is happy. His Majesty, King George is happy to hear that His Majesty, King Richard is happy. ---- Citizen Bob is happy to hear that His Majesty, King George is happy. ---- • Scenario • King Richard becomes ill • King Richard becomes happy • King George becomes ill • King George becomes happy • Remember, every man is happy when a king he serves is happy, but only a Noblemen is to be notified when his king is ill.

  12. Delegate Variance • Delegate definition:delegateObject Notify(King k); • Actual delegates:publicMan happy(Object other) {…}publicNobleman ill(Object other){…} • Variance: • Return Type: Co-Variant • Arguments Type: Contra-Variant • Static / Non-static: both static and non-static actuals may be used. • Compatibility Rules: Allow a specific listener to subscribe to a more general event distribution channel • It is OK to pass an actual King argument to the listener happy(Object other) • Event triggering expects an Object, and is type safe even if a Man or a Nobleman is returned.

  13. Delegate Type Hierarchy using System;usingSystem.Reflection; delegate Object MyDelegateType(Type o); publicstaticclassDelegateTypeHierarchy {privatestatic String pName(Type t) { as before... } privatestaticvoidancestory(Object o){ as before… } publicstaticvoid Main() {ancestory(newMyDelegateType(pName)); } } MyDelegateType inherits from System.MulticastDelegate System.MulticastDelegate inherits from System.Delegate System.Delegate inherits from System.Object System.Object inherits from null

  14. Reflection • Relevant namespaces: • System.Reflection; • System.Reflection.Emit; • The Reflection API allows a C# program to inspect itself • gets the type from an existing object • dynamically creates an instance of a type • invokes the type's methods • accesses fields and properties of the object • … • The Reflection API allows a C# program to manipulate itself • adds new types at runtime • adds new methods to a type at runtime • …

  15. Dynamic methods public delegate void PrintDelegate (); publicPrintDelegate Create(string message) { MethodInfowriteLineMethod = typeof(Console).GetMethod("WriteLine", new Type[]{typeof(string)} ); ModulecurrentModule = Assembly.GetExecutingAssembly().GetModules()[0]; DynamicMethod method = newDynamicMethod("PrintData", typeof(void), new Type[0], currentModule); ILGeneratorilGenerator = method.GetILGenerator(); ilGenerator.Emit( OpCodes.Ldstr, message); ilGenerator.Emit( OpCodes.Call, writeLineMethod); ilGenerator.Emit( OpCodes.Ret ); PrintDelegate ret = method.CreateDelegate(typeof(PrintDelegate ) ) asPrintDelegate; return ret; }

  16. Anonymous Methods • Anonymous methods represent a way to pass a code block as a delegate parameter. delegate void Printer(string s); classAnonymousMethods{ static void Main() { Printer p = delegate(string j) { System.Console.WriteLine(j); }; p("The delegate using the anonymous method is called."); p = new Printer(AnonymousMethods.DoWork); p("The delegate using the named method is called."); } static void DoWork(string k) { System.Console.WriteLine(k); } } The delegate using the anonymous method is called. The delegate using the named method is called.

  17. Anonymous Methods (2) delegate void Printer2(); classAnonymousMethods{ static void Main() { string j = "The delegate with local variable is called."; Printer2 p2 = delegate() { System.Console.WriteLine(j); }; p2(); } The delegate with local variable is called.

  18. Lambda Expressions • A lambda expressions is an anonymous function, that use the lambda operator =>. • The left side of the lambda operator specifies the input parameters (if any) • The right side holds the expression or statement block delegate void Printer(string s); classLambdaExpressions{ static void Main() { Printer p = j => System.Console.WriteLine(j); p("The delegate using the anonymous method is called."); } } The delegate using the anonymous method is called.

  19. Yield Return Iterator • "yield" keyword is used to iterate through objects returned by a method. class Team { String s1 = "Brayent"; String s2 = "Parker"; String s3 = "Pual"; publicIEnumerable<String> getPlyares() { for(int i = 1; i < 4; i++) switch (i) { case 1: yield return s1; break; case 2: yield return s2; break; case 3: yield return s3; break; } } static void Main() { Team t = new Team(); foreach(String player int.getPlyares()) Console.WriteLine(player); }

  20. More about Yield • An iterator is a method, get accessor or operator that enables you to support foreach iteration in a class or struct. • The yield statement can only appear inside an iterator block. • yield return <expression> • expression is evaluated and returned as a value to the enumerator object. • expression has to be implicitly convertible to the yield type of the iterator. • A yield return statement cannot be located anywhere inside a try-catch block. • A yield statement cannot appear in an anonymous method. • yield break • The operation unconditionally returns control to the caller of the iterator. • A yield break statement cannot be located in a finally block. • A yield statement cannot appear in an anonymous method.

  21. Extension methods • Extension methods are a special kind of static method • Extension methods allow to "add" methods to existing types without modifying the original type public static class Extension { public static boolIsNullOrEmpty(this string s) { return (s == null || s.Trim().Length == 0); } public static boolIsLengthEquals(this string s, int length){ return (s != null && s.Length == length); } } static void Main(string[] args) { string newString = null; if (newString.IsNullOrEmpty()) { // Do Something1 } if (newString.IsLengthEquals(3)) { // Do Something2 } }

  22. Rules for the extension methods • The first parameter specifies which type the method operates on • the parameter is preceded by this modifier • Extension methods can be used only when the namespace in which the methods are defined is explicitly imported with a using directive. • Extension methods cannot access private variables in the type they are extending • Extension methods can extend a class or interface • An extension method with the same name and signature as an interface or class method will never be called. • At compile time, extension methods always have lower priority than instance methods defined in the type itself

  23. Summary – C# Unique Features • Properties and Indexers: implement fields with functions • Conforms to Eiffel Principle of Uniform Reference. • Delegates: type safe function pointers • Events: list of delegates. • Static classes • Seamless integration of value semantics • Including nullable values. • Default Strict Inheritance • override and new keywords

More Related