1 Introduction to Web Application Advanced C#. 2 Topics Common Type System Delegate Event C# 2.0

Preview:

Citation preview

1

Introduction to Web Application

Advanced C#

2

Topics• Common Type System

• Delegate

• Event

• C# 2.0

3

CTS Overview

• An Introduction to the Common Type System

• Elements of the Common Type System

• Object-Oriented Characteristics

4

An Introduction to the Common Type System

• Common Type System Architecture

• Value Types vs. Reference Types

5

Common Type System Architecture

6

Value Types vs. Reference Types

• Value Types Are Primitive or User-Defined Structures– Allocated on stack– Assigned as copies– Default behavior is pass by value

• Reference Types Are Objects That Are:– Allocated on heap using the new keyword– Assigned as references– Passed by reference

7

Elements of the Common Type System

• Primitive Types

• Objects

• Constructors

• Properties

• Custom Types

• Enumerations

• Interfaces

8

Primitive Types

• Simple Small Types Common in Most Languages

• Naming Differences

• C# Support

• Conversions

9

Objects• Every Class Inherits from

System.Object

• Objects Specify Data and Behavior

• Fields Define the Data

• Methods Define the Behaviorclass Accumulator{ public float Result; public void Add(float amount) { Result += amount; }}

class Accumulator{ public float Result; public void Add(float amount) { Result += amount; }}

10

Constructors• Constructors Are Used to Initialize Classes

• Constructors Can Have Zero or More Parameters

class Rectangle{ private int x1,y1,x2,y2; public Rectangle(int x1, int y1, int x2,int y2) { this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; }}

class Rectangle{ private int x1,y1,x2,y2; public Rectangle(int x1, int y1, int x2,int y2) { this.x1 = x1; this.x2 = x2; this.y1 = y1; this.y2 = y2; }}

11

Properties

• Properties Are Similar to Fields

• Properties Use get and set Accessor Methods for Managing Data Values

public float Start{ get { return start; } set { if (start >= 0) start = value; }}

public float Start{ get { return start; } set { if (start >= 0) start = value; }}

12

Custom Types• Inherit from System.ValueType

• Are Defined with the struct Keyword in C#

• Can Have Methods, Properties, and Fields

struct Employee{ public string Name; public ushort Age; public DateTime HireDate; public float Tenure() { TimeSpan ts = DateTime.Now – HireDate; return ts.Days/(float)365; }}

struct Employee{ public string Name; public ushort Age; public DateTime HireDate; public float Tenure() { TimeSpan ts = DateTime.Now – HireDate; return ts.Days/(float)365; }}

13

Enumerations• .NET Framework Enumerations

– Inherit from System.Enum– Use the enum keyword

enum Color{

Red, //0Green, //1Blue //2

}

enum Color{

Red, //0Green, //1Blue //2

}

Color.Red;Color.Red;

14

Interfaces• An Interface Is a Contractual Description of

Methods and Properties• An Interface Has No Implementation• Use Casting in Client Code to Use an Interface

interface ICDPlayer{ void Play(short playTrackNum); void Pause(); void Skip(short numTracks); short CurrentTrack { get; set; }}

interface ICDPlayer{ void Play(short playTrackNum); void Pause(); void Skip(short numTracks); short CurrentTrack { get; set; }}

15

Object-Oriented Characteristics

• Abstraction

• Encapsulation

• Inheritance

• Polymorphism

16

Abstraction

• Abstraction Works from the Specific to the General

• Grouping Elements Makes It Easier to Work with Complex Data Types

• Abstraction Is Supported Through Classes

17

Encapsulation

• Encapsulation Is the Process of Hiding Internal Details of a Class

• Encapsulation Keywords– public– protected– protected internal– internal– private

• Type-Level Accessibility• Nested Classes

18

Inheritance

• Inheritance Is the Reuse of Class Members in Other Classes

• The Common Type System Only Supports Single Inheritance for Classes

• Member Hiding– Redefine the same method in the derived class– Use the new keyword

• Abstract Members• Sealed Classes

19

Polymorphism

• Polymorphism Allows a Reference Variable to Call the Correct Method

• Virtual Methods Enable Polymorphism in the Common Type System– Use the virtual keyword in the base class– Use the override keyword in the derived class

• Sealed Methods

20

A complex application

Expression e = new Operation(new VariableReference("x"),'*',

new Operation(new VariableReference("y"),'+',new Constant(2)));

public abstract class Expression{public abstract double Evaluate(Hashtable

vars);}

21

public class Constant: Expression{

double value;public Constant(double value) {

this.value = value;}public override double Evaluate(Hashtable vars) {

return value;}

}

22

public class VariableReference: Expression{

string name;public VariableReference(string name) {

this.name = name;}public override double Evaluate(Hashtable vars) {

object value = vars[name];if (value == null) {

throw new Exception("Unknown variable: " + name);

}return Convert.ToDouble(value);

}}

23

public class Operation: Expression{

Expression left;char op;Expression right;public Operation(Expression left, char op, Expression right) {

this.left = left;this.op = op;this.right = right;

}public override double Evaluate(Hashtable vars) {

double x = left.Evaluate(vars);double y = right.Evaluate(vars);switch (op) {

case '+': return x + y;case '-': return x - y;case '*': return x * y;case '/': return x / y;

}throw new Exception("Unknown operator");}}

24

Example

Expression e = new Operation(new VariableReference("x"),'+',new Constant(3));

Hashtable vars = new Hashtable();

vars["x"] = 3;

Console.WriteLine(e.Evaluate(vars));

25

e.Evalution

left.Evaluate(vars); right.Evaluate(vars);

Find x’s value in vars return Contant

e is a object of Operation, call Operation’s Evaluation

left is a object of VariableReference

right is a object of Contant

3+3=6

3 3

26

Overloadstatic void F() {

Console.WriteLine("F()");}static void F(object x) {

Console.WriteLine("F(object)");}static void F(int x) {

Console.WriteLine("F(int)");}static void F(double x) {

Console.WriteLine("F(double)");}static void F(double x, double y) {

Console.WriteLine("F(double, double)");}

27

Delegate and Event Overview

• Delegates

• Multicast Delegates

• Events

• When to Use Delegates, Events, and Interfaces

28

Java Programmingimport java.lang.reflect.*;public class HelloWorld {

public static void main(String[] args){try { Class c = Class.forName("HelloWorld"); Method[] methodList = c.getDeclaredMethods(); for (int i=0; i<methodList.length; i++){

System.out.println(methodList[i].toString()); } Method m = c.getMethod("hello", null); Object o = c.newInstance(); m.invoke(o, null);}}

public void hello(){ System.err.println("HelloWorld"); }}

catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();

} catch (NoSuchMethodException e){// TODO Auto-generated catch blocke.printStackTrace();

} catch (InstantiationException e){// TODO Auto-generated catch blocke.printStackTrace();

} catch (IllegalAccessException e){// TODO Auto-generated catch blocke.printStackTrace();

} catch (InvocationTargetException e){// TODO Auto-generated catch blocke.printStackTrace();

}

catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();

} catch (NoSuchMethodException e){// TODO Auto-generated catch blocke.printStackTrace();

} catch (InstantiationException e){// TODO Auto-generated catch blocke.printStackTrace();

} catch (IllegalAccessException e){// TODO Auto-generated catch blocke.printStackTrace();

} catch (InvocationTargetException e){// TODO Auto-generated catch blocke.printStackTrace();

}

29

Delegates

• Delegate Scenario

• Declaring a Delegate

• Instantiating a Delegate

• Calling a Delegate

30

Delegate Scenario

1 - Change in switch position invokes switch’s OnFlip method

2 - OnFlip Method invokes delegate

3 - Delegate invokes light’s OnFlipCallback method

4 - OnFlipCallback method changes light’s state

OnFlip method

Switch Object

OnFlipCallbackmethod

Light Object

Delegate objectDelegate object

OnFlip method

Switch Object

31

Declaring a Delegate

• A Delegate Declaration Defines a Type That Encapsulates a Method with a Particular Set of Arguments and Return Type

// declares a delegate for a method that takes a single// argument of type string and has a void return type delegate void MyDelegate1(string s);

// declares a delegate for a method that takes a single// argument of type string and has a void return type delegate void MyDelegate1(string s);

32

Instantiating a Delegate

• A Delegate Object Is Created with the new Operator

• Delegate Objects Are Immutable

// instantiating a delegate to a static method Hello// in the class MyClassMyDelegate1 a = new MyDelegate1(MyClass.Hello);

// instantiating a delegate to an instance method// AMethod in object pMyClass p = new MyClass(); MyDelegate1 b = new MyDelegate1(p.AMethod);

// instantiating a delegate to a static method Hello// in the class MyClassMyDelegate1 a = new MyDelegate1(MyClass.Hello);

// instantiating a delegate to an instance method// AMethod in object pMyClass p = new MyClass(); MyDelegate1 b = new MyDelegate1(p.AMethod);

33

Calling a Delegate

• Use a Statement Containing: – The name of the delegate object– Followed by the parenthesized arguments to be

passed to the delegate

// given the previous delegate declaration and// instantiation, the following invokes MyClass'// static method Hello with the parameter "World"

a("World");

// given the previous delegate declaration and// instantiation, the following invokes MyClass'// static method Hello with the parameter "World"

a("World");

34

Multicast Delegates

• Multicast Delegate Scenario

• Single vs. Multicast Delegates

• Creating and Invoking Multicast Delegates

• C# Language-Specific Syntax

• Delegate Details

35

Multicast Delegate Scenario

2 - OnFlip method invokes multicast delegate1

4 - OnFlipCallback method changes light1’s state

3 - delegate1 invokes light1’s OnFlipCallback

7 - OnFlipCallback method changes light2’s state

6 - delegate2 invokes light2’s OnFlipCallback

OnFlip method

Switch Object

OnFlipCallbackmethod

Light1 Object

OnFlipCallbackmethod

Light2 Object

Multicast delegate1 objectMulticast delegate1 object

Multicast delegate2 objectMulticast delegate2 object

Invocation list

5 - delegate2 is invoked

1 - Change in switch position invokes switch’s OnFlip method

OnFlip method

Switch Object

36

Single vs. Multicast Delegates• All Delegates Have an Invocation List of Methods That Are

Executed When Their Invoke Method is Called• Single-Cast Delegates: Derived Directly From

System.MulticastDelegate– Invocation list contains only one method

• Multicast Delegates: Derived from System.MulticastDelegate– Invocation list may contain multiple methods– Multicast delegates contain two static methods to add and remove

references from invocation list: Combine and Remove• Use GetInvocationList to Obtain an Invocation List as an Array

of Delegate References • Use a Delegate’s Target and Method Properties to Determine:

– Which object will receive the callback– Which method will be called

37

Creating and Invoking Multicast Delegates

// assign to c the composition of delegates a and b c = (MyDelegate2)Delegate.Combine(a, b);  // assign to d the result of removing a from c d = (MyDelegate2)Delegate.Remove(c, a);  // Iterate through c's invocation list // and invoke all delegates except a Delegate[] DelegateList = c.GetInvocationList();for (int i = 0; i < DelegateList.Length; i++) { if (DelegateList[i].Target != aFoo1) {

((MyDelegate2) DelegateList[i])();}

}

// assign to c the composition of delegates a and b c = (MyDelegate2)Delegate.Combine(a, b);  // assign to d the result of removing a from c d = (MyDelegate2)Delegate.Remove(c, a);  // Iterate through c's invocation list // and invoke all delegates except a Delegate[] DelegateList = c.GetInvocationList();for (int i = 0; i < DelegateList.Length; i++) { if (DelegateList[i].Target != aFoo1) {

((MyDelegate2) DelegateList[i])();}

}

38

C# Language-Specific Syntax• C# Delegates That Return Void Are Multicast

Delegates

• In C#, Use the + and - Operators to Add and Remove Invocation List Entries– Less verbose than Combine and Remove methods

MyDelegate a, b, c, d;a = new MyDelegate(Foo);b = new MyDelegate(Bar);c = a + b; // Compose two delegates to make anotherd = c - a; // Remove a from the composed delegatea += b; // Add delegate b to a's invocation lista -= b; // Remove delegate b from a's list

MyDelegate a, b, c, d;a = new MyDelegate(Foo);b = new MyDelegate(Bar);c = a + b; // Compose two delegates to make anotherd = c - a; // Remove a from the composed delegatea += b; // Add delegate b to a's invocation lista -= b; // Remove delegate b from a's list

39

Demonstration: Delegates

40

codeusing System;namespace TestApp{

delegate void D(int x);class Test{

static void Main() {

C c = new C();D cd1 = new D(c.M1);D cd2 = new D(C.M2);D cd3 = cd1 + cd2 + cd2 + cd1;// M1 + M2 + M2 +

M1cd3(10);

cd3 -= cd1; // => M1 + M2 + M2cd3(20);cd3 = cd1 + cd2 + cd2 + cd1; // M1 + M2 + M2 + M1cd3 -= cd1 + cd2; // => M2 + M1cd3(30);cd3 = cd1 + cd2 + cd2 + cd1; // M1 + M2 + M2 + M1cd3 -= cd2 + cd2; // => M1 + M1cd3 = cd1 + cd2 + cd2 + cd1; // M1 + M2 + M2 + M1cd3 -= cd2 + cd1; // => M1 + M2cd3 = cd1 + cd2 + cd2 + cd1; // M1 + M2 + M2 + M1cd3 -= cd1 + cd1; // => M1 + M2 + M2 + M1

}}

}

41

class C

{

public void M1(int i)

{ Console.WriteLine("1 Hello "+i); }

public static void M2(int i)

{ Console.WriteLine("2 Hello "+i); }

}

42

Delegate Details

• A Delegate Declaration Causes the Compiler to Generate a New Class

// delegate void MyDelegate3(string val);  class MyDelegate3 : System.MulticastDelegate {

public MyDelegate3(object obj, methodref mref) : base (obj, mref) { //...} public void virtual Invoke(string val) { //... }

};

// delegate void MyDelegate3(string val);  class MyDelegate3 : System.MulticastDelegate {

public MyDelegate3(object obj, methodref mref) : base (obj, mref) { //...} public void virtual Invoke(string val) { //... }

};

43

Events

• Event Scenario

• Declaring an Event

• Connecting to an Event

• Raising an Event

44

Event ScenarioMouse Object

MouseClicked field Invocation List:

remove_MouseClicked method

add_MouseClicked method

OnMouseClicked method

add_MouseClicked method

SoundMaker Object

MouseClicked methodMouseClicked method

multicast delegate objectmulticast delegate object

OnMouseClicked method

stopButton object

MouseClicked methodMouseClicked method

multicast delegate objectmulticast delegate object

MouseClicked methodMouseClicked method

MouseClicked methodMouseClicked method

multicast delegate object

remove_MouseClicked method

45

Declaring an Event

• An event is a member that enables a class or object to provide notifications. An event is declared like a field except that the declaration includes an event keyword and the type must be a delegate type.

// MouseClicked delegate declaredpublic delegate void MouseClickedEventHandler();

public class Mouse {

// MouseClicked event declaredpublic static event MouseClickedEventHandler

MouseClicked;//...

}

// MouseClicked delegate declaredpublic delegate void MouseClickedEventHandler();

public class Mouse {

// MouseClicked event declaredpublic static event MouseClickedEventHandler

MouseClicked;//...

}

46

Connecting to an Event

• Connect by Combining Delegates

• Disconnect by Removing Delegates

// Client’s method to handle the MouseClick eventprivate void MouseClicked() { //...}//...

// Client code to connect to MouseClicked event Mouse.MouseClicked += new

MouseClickedEventHandler(MouseClicked);

// Client code to break connection to MouseClick eventMouse.MouseClicked -= new

MouseClickedEventHandler(MouseClicked);

// Client’s method to handle the MouseClick eventprivate void MouseClicked() { //...}//...

// Client code to connect to MouseClicked event Mouse.MouseClicked += new

MouseClickedEventHandler(MouseClicked);

// Client code to break connection to MouseClick eventMouse.MouseClicked -= new

MouseClickedEventHandler(MouseClicked);

47

Raising an Event

• Check Whether Any Clients Have Connected to This Event– If the event field is null, there are no clients

• Raise the Event by Invoking the Event’s Delegate

if (MouseClicked != null) MouseClicked();

if (MouseClicked != null) MouseClicked();

48

• Name Events with a Verb and Use Pascal Casing • Use “Raise” for Events, Instead of “Fire”• Event Argument Classes Extend System.EventArgs• Event Delegates Return Void and Have Two

Arguments• Use a Protected Virtual Method to Raise Each Event

public class SwitchFlippedEventArgs : EventArgs { //... }

public delegate void SwitchFlippedEventHandler(object sender, SwitchFlippedEventArgs e);

public event SwitchFlippedEventHandler SwitchFlipped;

public class SwitchFlippedEventArgs : EventArgs { //... }

public delegate void SwitchFlippedEventHandler(object sender, SwitchFlippedEventArgs e);

public event SwitchFlippedEventHandler SwitchFlipped;

.NET Framework Guidelines

49

When to Use Delegates, Events, and Interfaces

• Use a Delegate If: – You basically want a C-style function pointer– You want single callback invocation– The callback should be registered in the call or at

construction time, not through an add method call

• Use Events If: – Client signs up for the callback function through an add

method call– More than one object will care – You want end users to be able to easily add a listener to the

notification in the visual designer

• Use an Interface If: – The callback function entails complex behavior,

such as multiple methods

50

C# 2.0 Overview• Generics

– Generic types are added to the language to enable programmers to achieve a high level of code reuse and enhanced performance for collection classes. Generic types can differ only by arity. Parameters can also be forced to be specific types. See Generic Type Parameters (C#) for more information.

• Iterators – Iterators make it easier to dictate how a foreach loop will

iterate over a collection's contents • Partial Class

– Partial type definitions allow a single type, such as a class, to be split into multiple files. The Visual Studio designer uses this feature to separate its generated code from user code

• …

Recommended