33) static void Main() { Action operations = MathOperations.MultiplyByTwo; operations += MathOperations.Square; ProcessAndDisplayNumber(operations, 2.0);

Slides:



Advertisements
Similar presentations
Introduction to Web Application
Advertisements

Clonazione La clonazione... Ovvero: come costruire una copia (probabilmente che ritorni true su equals?)
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
Nov 2005 MSc Slide 1 - Another Example of a Structural Pattern Alternative way of adding Functionality to an existing class (alternative to a derived class)
Module 12: Operators, Delegates, and Events. Overview Introduction to Operators Operator Overloading Creating and Using Delegates Defining and Using Events.
 2007 Dr. Natheer Khasawneh. Chapter 13. Graphical User Interface Concepts: Part 1.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Arrays & Enum & Events. Arrays Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entities—they remain.
CS  C++ Function Pointers  C# Method References  Groundwork for Lambda Functions.
Mads Torgersen Language PM for C# What’s new in C# 6.0.
March Ron McFadyen1 Composite Used to compose objects into tree structures to represent part-whole hierarchies Composite lets clients treat.
CS 4800 By Brandon Andrews.  Specifications  Goals  Applications  Design Steps  Testing.
Exception examples. import java.io.*; import java.util.*; class IO { private String line; private StringTokenizer tokenizer; public void newline(DataInputStream.
Programming Handheld and Mobile devices 1 Programming of Handheld and Mobile Devices Lecture 20 Microsoft’s Approach 3 – C# Rob Pooley
16-Aug-15 Java Puzzlers From the book Java Puzzlers by Joshua Bloch and Neal Gafter.
C# Event Processing Model Solving The Mystery. Agenda Introduction C# Event Processing Macro View Required Components Role of Each Component How To Create.
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
Crossword Puzzle Solver Michael Keefe. Solver structure.
Extension Methods Programming in C# Extension Methods CSE Prof. Roger Crawfis.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
Module 3: Working with Components. Overview An Introduction to Key.NET Framework Development Technologies Creating a Simple.NET Framework Component Creating.
Delegates Programming in C# Delegates CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
private void Goto2(object sender, Windows.UI.Xaml.RoutedEventArgs e) { var app = App.Current as Common.BootStrapper; var nav = app.NavigationService;
.NET 2.0 and Visual Studio 2005 SigWin Outline Language enhancements in C# Language enhancements in C# –Generics –Partial types –Anonymous methods.
Lecture 16: Multithreaded Programming. public partial class Form1 : Form { Thread ct; Thread rt; public static int circle_sleep = 0; public static int.
Sample Application Multi Layered Architecture (n-tier): –Graphical User Interface (GUI): Forms, components, controls The Visual Designer in Visual Studio.
ILM Proprietary and Confidential -
Delegates and Events Callback Functionality and Event-Driven Programming Svetlin Nakov Technical Trainer Software University
Rules Two Teams Questions worth 1-3 points – Entire team can confer to answer the question – Max of 2 minutes per question – You can use a computer on.
Neal Stublen What’s an indexer?  An array has an indexer… int[] myArray = new int[5]; for (int index = 0; index < 5; ++index) {
CSC 270 – Survey of Programming Languages C++ Lecture 6 – Exceptions.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.

Variables and Data Types.  Variable: Portion of memory for storing a determined value.  Could be numerical, could be character or sequence of characters.
Problems.Net Анатолий Крыжановский Обра. ООП 2 class Bar { } void Foo(object a) { Console.WriteLine("object"); } void Foo(object a, object b) { Console.WriteLine("object,
Callback Functionality and Event-Driven Programming
Bill Campbell, UMB Microsoft's.NET C# and The Common Language Runtime.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 10 th Lecture Pavel Ježek
Neal Stublen Tonight’s Agenda  Indexers  Delegates and events  Operator overloading  Class inheritance  Q&A.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Generics Ashima Wadhwa. What are generics Generics were added by C# 2.0 the term generics means parameterized types. Using generics, you can define a.
Outline Class and Object-Oriented Programing –Encapsulation and inheritance Example –Commission Employee –Encapsulation and inheritance Strings and Formatting.
From C++ to C# Part 5. Enums Similar to C++ Similar to C++ Read up section 1.10 of Spec. Read up section 1.10 of Spec.
Chapter 9 Delegates and Events. Copyright 2006 Thomas P. Skinner2 Delegates Delegates are central to the.NET FCL A delegate is very similar to a pointer.
Architecture Multi Layered Architecture (n-tier): Application: Model Controllers Database Access Graphical User Interface (GUI): Forms, components, controls.
1) int i = int.Parse("99"); 2) delegate void IntMethodInvoker(uint x); 3) delegate double TwoLongsOp(long first, long second); 4) delegate string GetAString();
C# 6 - do it right Vedran Kaldi Senior
Effective C# 50 Specific Way to Improve Your C# Item 22, 23.
V 1.0 OE-NIK HP 1 Advanced Programming Delegates, Events.
Arrays & Enum & Events. Arrays Arrays are data structures consisting of related data items of the same type. Arrays are fixed-length entities—they remain.
CIS NET Applications1 Chapter 6 – Events. CIS NET Applications2 Objectives Delegate-based Events.NET event support Practical guides for managing.
Module 5: Programming with C#. Overview Using Arrays Using Collections Using Interfaces Using Exception Handling Using Delegates and Events.
Andres Käver, IT Kolledž public interface IPersonRepository : IDisposable { IQueryable All { get; } IQueryable AllIncluding( params Expression.
Delegates and Events Svetlin Nakov Telerik Corporation
How to work with indexers, delegates, events, and operators
Advanced .NET Programming I 4th Lecture
Computing with C# and the .NET Framework
Reserved Words.
Functions Used to write code only once Can use parameters.
C# Event Processing Model
null, true, and false are also reserved.
בניית מחלקות.
Exception Handling CSCI293 - C# October 3, 2005.
Delegates & Events 1.
Java Lesson 36 Mr. Kalmes.
CSC 270 – Survey of Programming Languages
Web Service.
Module 2 Variables, Assignment, and Data Types
鄭士康 國立台灣大學 電機工程學系/電信工程研究所/ 資訊網路與多媒體研究所
Events, Delegates, and Lambdas
Presentation transcript:

33) static void Main() { Action operations = MathOperations.MultiplyByTwo; operations += MathOperations.Square; ProcessAndDisplayNumber(operations, 2.0); ProcessAndDisplayNumber(operations, 7.94); ProcessAndDisplayNumber(operations, 1.414); Console.WriteLine() ; } 34) MulticastDelegate ProcessAndDisplayNumber вызван со значением value = 2 Умножение на 2: 2 дает 4 Возведение в квадрат: 2 дает 4 ProcessAndDisplayNumber вызван со значением value =7.94 Умножение на 2: 7.94 дает Возведение в квадрат: 7.94 дает ProcessAndDisplayNumber вызван со значением value = Умножение на 2: дает Возведение в квадрат: дает

35) using System; namespace Wrox.ProCSharp.Delegates { class Program { static void One() { Console.WriteLine("One"); throw new Exception("Ошибка в One"); } static void Two() { Console.WriteLine("Two"); }

36) static void Main() { Action d1 = One; d1 += Two; try { d1(); } catch (Exception) { Console.WriteLine("Произошло исключение"); } 37) One Произошло исключение

38) static void Main() { Action d1 = One; d1 += Two; Delegate[] delegates = d1.GetInvocationList(); foreach (Action d in delegates) { try { d() ; } catch (Exception) { Console.WriteLine("Произошло исключение"); } 39) One Произошло исключение Two

40) using System; namespace Wrox.ProCSharp.Delegates { class Program { static void Main() { string mid = ", средняя часть,"; Func anonDel = delegate(string param) { param += mid; param += " а это добавлено к строке." ; return param; }; Console.WriteLine(anonDel("Начало строки")); }

41) using System; namespace Wrox.ProCSharp.Delegates { class Program { static void Main() { string mid = ", средняя часть,"; Func lambda = param => { param += mid; param += " а это добавлено к строке."; return param; }; Console.WriteLine(lambda("Начало строки”)); }

42) Func oneParam = s => String.Format( "изменение регистра {0} ", s.ToUpper()); Console.WriteLine(oneParam("test")); 43) Func twoParams = (x, y) => x * y; Console.WriteLine(twoParams (3, 2)); 44) Func twoParamsWithTypes = (double x, double y) => x * y; Console.WriteLine(twoParamsWithTypes(4, 2)); 45) Func square = х => х * х; 46) Func square = х => { return х * х; } 47) Func lambda = param => { param += mid; param += " а это добавлено к строке." ; return param; };

48) int someVal = 5; Func f = x => x + someVal; 49) someVal = 7; Console.WriteLine(f(3)) ; 50) public class AnonymousClass { private int someVal; public AnonymousClass(int someVal) { this.someVal = someVal; } public int AnonymousMethod(int x) { return x + someVal; }

51) using System; namespace Wrox.ProCSharp.Delegates { public class CarInfoEventArgs: EventArgs { public CarInfoEventArgs(string car) { this.Car = car; } public string Car {get; private set;} } public class CarDealer { public event EventHandler NewCarInfo; public void NewCar(string car) { Console.WriteLine("CarDealer, новый автомобиль {0}", car); if (NewCarlnfo != null) { NewCarlnfo(this, new CarlnfoEventArgs (car) ) ; }

52) public event EventHandler NewCarlnfo; 53) public delegate void EventHandler (object sender, TEventArgs e) where TEventArgs: EventArgs 54) private delegate EventHandler newCarInfo; public event EventHandler NewCarlnfo { add { newCarlnfo += value; } remove { newCarInfo = value; }

55) public void NewCar(string car) { Console.WriteLine("CarDealer, новый автомобиль {0}", car); if (NewCarlnfo != null) { NewCarlnfo(this, new CarlnfoEventArgs(car)); } 56) using System; namespace Wrox.ProCSharp.Delegates { public class Consumer { private string name; public Consumer(string name) { this.name = name; } public void NewCarIsHere(object sender, CarInfoEventArgs e) { Console.WriteLine ("{0}: автомобиль {1} является новым", name, e.Car); }

57) namespace Wrox.ProCSharp.Delegates { class Program { static void Main() { var dealer = new CarDealer(); var michael = new Consumer("Michael"); dealer.NewCarInfo += michael.NewCarIsHere; dealer.NewCar("Mercedes"); var nick = new Consumer ("Nick"); dealer.NewCarInfo += nick.NewCarIsHere; dealer.NewCar("Ferrari"); dealer.NewCarInfo = michael.NewCarlsHere; dealer.NewCar("Toyota"); }

58) CarDealer, новый автомобиль Mercedes Michael: автомобиль Mercedes является новым CarDealer, новый автомобиль Ferrari Michael: автомобиль Ferrari является новым Nick: автомобиль Ferrari является новым CarDealer, новый автомобиль Toyota Nick: автомобиль Toyota является новым 59) using System.Windows; namespace Wrox.ProCSharp.Delegates { public class WeakCarInfoEventManager: WeakEventManager { public static void AddListener(object source, IWeakEventListener listener) { CurrentManager.ProtectedAddListener(source, listener); } public static void RemoveListener(object source, IWeakEventListener listener) { CurrentManager.ProtectedRemoveListener(source, listener); }

public static WeakCarInfoEventManager CurrentManager { get { WeakCarInfoEventManager manager = GetCurrentManager(typeof(WeakCarInfoEventManager)) as WeakCarInfoEventManager; if (manager == null) { manager = new WeakCarInfoEventManager(); SetCurrentManager(typeof(WeakCarlnfoEventManager), manager); } return manager; } protected override void StartListening(object source) { (source as CarDealer).NewCarInfo += CarDealer_NewCarInfo; }

void CarDealer_NewCarInfo(object sender, CarInfoEventArgs e) { DeliverEvent(sender, e); } protected override void StopListening(object source) { (source as CarDealer).NewCarInfo = CarDealer_NewCarInfo; }

60) using System; using System.Windows; namespace Wrox.ProCSharp.Delegates { public class Consumer: IWeakEventListener { private string name; public Consumer(string name) { this.name = name; } public void NewCarIsHere(object sender, CarInfoEventArgs e) { Console.WriteLine ("{0} : автомобиль {1} является новым", name, e.Car); } bool IWeakEventListener.ReceiveWeakEvent(Type manager Type, object sender, EventArgs e) { NewCarIsHere(sender, e as CarInfoEventArgs); return true; }

61) static void Main() { var dealer = new CarDealer() ; var michael = new Consumer("Michael") ; WeakCarInfoEventManager.AddListener(dealer, michael); dealer.NewCar("Mercedes") ; var nick = new Consumer("Nick") ; WeakCarInfoEventManager.AddListener(dealer, nick); dealer.NewCar("Ferrari"); WeakCarInfoEventManager.RemoveListener(dealer, michael); dealer.NewCar("Toyota”); }