Скачать презентацию C hello cs using System public class My Скачать презентацию C hello cs using System public class My

dc0f7d5f60c8f4dbd905c1eae1dc7b7d.ppt

  • Количество слайдов: 36

C# hello. cs using System; public class My. Class { public static void Main() C# hello. cs using System; public class My. Class { public static void Main() { Console. Write. Line("Hello, World!"); } C: > csc hello. cs … … C: > hello. exe Hello, World!

Genealogy • Designer: Anders Hejlsberg (Microsoft) – Designer of Turbo Pascal, Visual J++, Delphi Genealogy • Designer: Anders Hejlsberg (Microsoft) – Designer of Turbo Pascal, Visual J++, Delphi (Borland) • C Dynasty: Play on Words – C++ increment C by one. – C# the musical note half tone above C • Yet another curly bracket programming language – – Grouping: {} Terminstic camp: statements terminated by "; " C operators: ++ % != += && & ^, >>, ? : … C like control: • if () … else … • for (…; …; …) … break … also multi-level break • while (…) … continue … also multi-level continue • do … while (…) • switch (…) … case … default no fall through, also switch on strings 2

Design Principles • All the Good Things: – Simplicity, General Purpose, Portability, Object Oriented Design Principles • All the Good Things: – Simplicity, General Purpose, Portability, Object Oriented • Programmer Protection: – – – Strong Nominative Typing Array Bounds Checking Garbage Collection Check against using uninitialized variables No "hiding" by inner scopes • Evolutionary: dramatic changes in each language version – Learn from Java mistakes: (no checked exceptions, since Anders Hejlsberg doesn't know yet how to do these right) • Efficiency: Not at any price • Better Java? – Developed by Microsoft – Compiles to the CLR "Common Language Interface" – Support for "unsafe" features, including pointers. 3

Pre-Defined Types • Integral Types (signed and unsigned version) : byte, short, ushort, int, Pre-Defined Types • Integral Types (signed and unsigned version) : byte, short, ushort, int, uint, long, ulong • May cause conversion problems. • Most programmers like byte to be unsigned. • Real Numbers: float, double, decimal (28 digits) • Other: bool, char (unicode), string (immutable unicode), 4

Value/Reference Semantics • Value Types – Simple types: char, int, float, … – Enum Value/Reference Semantics • Value Types – Simple types: char, int, float, … – Enum types public enum Color {Red, Blue, Green – Struct types } public struct Point { public int x, y; } • Reference Types – Classes, Interfaces, Delegates • Nullable Value Types char? c = eof() ? null : getchar(); if (c == null) … char c = c ? ? ' '; 5

Object Oriented Purity • Global Variables? No. – All variables are defined in functions/classes. Object Oriented Purity • Global Variables? No. – All variables are defined in functions/classes. • Global Routines? No. – All routines (functions) are defined in classes. • Non OO Types? No. – Even primitive types belong in the OO hierarchy. • OO Control Flow? No. – If, while, for, … are imperative statements • Preprocessor? Yes. (a good preprocessor can be used to defeat any paradigm) – Allows variables, but not parameterized macros. 6

Inheritance Hierarchy • Classes: – Single Inheritance – Common root: System. Object – Unified Inheritance Hierarchy • Classes: – Single Inheritance – Common root: System. Object – Unified type system: includes all builtin types (except for void) • System. Value. Type: base class of all value types – Implementation by seamless auto-boxing and auto-unboxing. • System. Enum: base class of all enum types • System. Array: base class of all arrays • … – Unextendable classes: denoted by keyword sealed – Static classe: denoted by keyword static • No non-static members • Must inherit form System. Object • Interfaces: – Multiple Inheritance hierarchy – May be implemented by classes and structs • Structs: no inheritance, but may implement interfaces. 7

Reflection 3 Levels: similar to Java and little-Smallatk using System; using System. Reflection; public Reflection 3 Levels: similar to Java and little-Smallatk using System; using System. Reflection; public static class Find. Levels { private static void traverse(Object o) { for (int n = 0; ; o = o. Get. Type()) { Console. Write. Line( "L"+ ++n + ": " + o + ". Get. Type() = " + o. Get. Type()); if (o == o. Get. Type()) break; } } public static void Main() { traverse (3. 1415926); } } L 1: 3. 1415926. Get. Type() = System. Double L 2: System. Double. Get. Type() = System. Runtime. Type L 3: System. Runtime. Type. Get. Type() = System. Runtime. Type 8

Exploring Hierarchy with Reflection using System; using System. Reflection; public static class Find. Super. Exploring Hierarchy with Reflection using System; using System. Reflection; public static class Find. Super. Types { private static String p. Name(Type t) { return t. Base. Type == null ? "null" : t. Base. Type. To. String(); } private static void ancestory(Object o) { for (Type t = o. Get. Type(); t != null ; t = t. Base. Type) Console. Write. Line(t + " inherits from " + p. Name(t)); } public static void Main() { ancestory(3. 1415926. Get. Type()); } } System. Runtime. Type inherits from System. Reflection. Member. Info inherits from System. Object inherits from null 9

Covariance • Suppose B is a subtype class A{}; of A: then an array Covariance • Suppose B is a subtype class A{}; of A: then an array of B void f(A[] a) { is a subtype of an array of a[0] = new A(); //OK? A. } Like Java, unlike C++. • Runtime type checking: in class B: A {} assignments to array elements. // Legal assignment • No Array Covariance of A[] x = new B[]; Value types. Object a[] = new int[5]; // Legal call // error f(x); • Method arguments and return type are novariant. 10

A Universal Dump Array Function class EM: ICloneable { // Will dump any array A Universal Dump Array Function class EM: ICloneable { // Will dump any array thanks to array co-variance public static void print( String title, Object[] array) { if (array. Length == 0) return; Console. Write. Line(title + ": "); foreach (Object item in array) Console. Write. Line(" " + item); Console. Write. Line(); } // No co-variance of return type of methods public Object Clone() { return new EM(); } … } 11

 • Five Levels Accessibility public Unlimited access protected This class and all subclasses • Five Levels Accessibility public Unlimited access protected This class and all subclasses internal Classes define in this "assembly" protected internal This assembly and subclasses • Nicknamed internal public – private This class only – – • Default Levels – – – namespace enum class interface struct others public private internal 12

Class/Struct Member Kinds • Instance Constructors: similar to C++/Java constructors – Dynamic binding within Class/Struct Member Kinds • Instance Constructors: similar to C++/Java constructors – Dynamic binding within constructors • Finalizer: Syntax as C++ destructor; semantics as Java finalizer. • Static Constructors: similar to Java static initiliazers • Constants: value computed at compile time – implicitly static • Instance Fields: like Java/C++ • Instance Readonly Fields: with readonly keyword – initialized by constructor / static constructor • Static Fields: with static keyword • Static Readonly Fields: Initialized by static constructor only • Methods & Static Methods: like Java/C++ • Properties (and static properties): field access implemented by methods • Indexers: array access implemented by methods • Events (and Static Events): more on these later 13

Investigating Member Kinds public class EM: ICloneable { public static void print(…) { … Investigating Member Kinds public class EM: ICloneable { public static void print(…) { … } public Object Clone() { … } static readonly public String NL = "n"; public static void Main() { Type t = new EM(). Get. Type(); Console. Write. Line(t+": "+t. Attributes + NL); } print("Constructors", t. Get. Constructors()); print("Methods", t. Get. Methods()); print("Properties", t. Get. Properties()); print("Fields", t. Get. Fields()); print("Events", t. Get. Events()); print("Interfaces", t. Get. Interfaces()); } 14

Reflection Information EM: Auto. Layout, Ansi. Class, Public, Before. Field. Init Constructors: Void. ctor() Reflection Information EM: Auto. Layout, Ansi. Class, Public, Before. Field. Init Constructors: Void. ctor() Methods: Void print(System. String, System. Object[]) System. Object Clone() Void Main() System. Type Get. Type() System. String To. String() Boolean Equals(System. Object) Int 32 Get. Hash. Code() Fields: System. String NL Interfaces: System. ICloneable 15

Properties • Property: a field implemented with methods • Varieties: read only, write only, Properties • Property: a field implemented with methods • Varieties: read only, write only, read-write • Contextual keywords: get, set, value (also add and del for events) – Provide specific meaning in the code – Not reserved words public struct Window { public int n_read = 0; private string title; public string Title { // read-write property get { // property getter method n_read++; return title; } set { // property setter method if (title != value)// implicit parameter return; title = value; redraw(); } } Window w = new Window("Initial Title"); … Console. Write. Line(w. Title); // increment n_read } w. Title = "My Title"; // redraw 16

Static Properties public struct Harry. Potter. Book { static private int count; static Harry. Static Properties public struct Harry. Potter. Book { static private int count; static Harry. Potter. Book() {// static constructor count = she_wrote_it() ? 7 : 6; } static public int Count { // read-only static property get { return count; } } … } 17

Static Members • A Node With a Static Allocator class Node { public Node Static Members • A Node With a Static Allocator class Node { public Node Next; public String Key; public Object Data; public Node(Node next) : this(null, next) { } public Node(String key, Object data, Node next) { Key = key; Data = data; Next = next; } static public Node Allocate(uint n) { return n == 0 ? null : new Node(Allocate(n - 1)); } } • A List Using the Static Allocator class List { private Node first; public List(uint n) { first = Node. Allocate(n); } … } 18

Indexers • Purpose: Implement array access with methods • Similar to properties (though no Indexers • Purpose: Implement array access with methods • Similar to properties (though no static indexers) – Syntax: modifiers return. Type this[Index. Type pos] – Variations: • multi-parameters indexers • read-only, write-only and read-write indexers • overloaded indexers class List { … private Node nth(Node n, uint d) { if (n == null) throw new Exception("out of range"); return d == 0 ? n : nth(n. Next, d-1); } public Object this[uint i] { // indexer using ordinal position get { return nth(first, i). Data; } set { nth(first, i). Data = value; } } … } 19

Using the Indexer class List { static void Main() { const uint n = Using the Indexer class List { static void Main() { const uint n = 5; List sq = new List(n); for (uint i = 0; i < n; i++) sq[i] = i * i; for (uint i = 0; i < n; i++) Console. Write. Line(i + "^2 = " + sq[i]); } } 0^2 = 0 1^2 2^2 3^2 4^2 = = 1 4 9 16 20

Indexer Overloading public class List { … private static Node find(Node n, String k) Indexer Overloading public class List { … private static Node find(Node n, String k) { if (n == null) return null; return n. Key. Equals(k) ? n : find(n. Next, k); } public Object this[String k] { // indexer using key get { Node n = find(first, k); return n != null ? n. Data : null; } set { Node n = find(first, k); if (n != null) n. Data = value; else first = new Node(k, value, first); } } } 21

Using String Indexer class List { static void Main() { … List capitals = Using String Indexer class List { static void Main() { … List capitals = new List(0); capitals["Israel"] = "Jerusaelm"; capitals["Iraq"] = "Bagdad"; Console. Write. Line(capitals["Israel"]); } } Jerusalem 22

Inheritance and Binding • Method Binding: static, unless method is declared virtual – virtual Inheritance and Binding • Method Binding: static, unless method is declared virtual – virtual modifier cannot go with any of static, abstract, private or override modifiers. – Properties can be virtual • Overriding: inheritance is strict by default. – Overriding methods must be declared as such with override keyword – Cannot override non-virtual functions – Use new modifier to indicate hiding • Sealing: use sealed keyword to indicate that an overriding function cannot be overridden further – No point in sealing a "plain" virtual function. 23

Events and Delegates • C# Terminology – Event: a field representing a multi-set of 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 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. 24

King, Nobleman and Citizens Kingdom Life static Citizen sealed namespace Man abstract Nobleman concrete King, Nobleman and Citizens Kingdom Life static Citizen sealed namespace Man abstract Nobleman concrete Notify delegate King concrete State enum • Name: every man has a name • Title: every man has a title, based on his status and name – Realized by method To. String() • Service: every man can be set to service any number of kings. – Method service(King k) in class Person 25

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

Class King and Enum State namespace Kingdom { State … enum State { happy, Class King and Enum State namespace Kingdom { State … enum State { happy, ill }; class King : Man { public State s; public King(String name): base(name){ s = State. ill; } sealed override public String To. String() { return "His Majesty, King " + Name; King } concrete // public multi-sets of those interested in the King's being. public event Notify when_ill, when_happy; public Object become_ill() { // returns last listener return value state = State. ill; return when_ill != null ? when_ill(this) : null; } public void become_happy() { // returns last listener return value state = State. happy; return when_happy != null ? when_happy(this) : null; } … } } 27

Class Man namespace Kingdom { abstract class Man { protected readonly String Name; public Class Man namespace Kingdom { abstract class Man { protected readonly String Name; public Man(String name) { Name = name; } abstract override public String To. String(); // Every man is happy when a King he serves is happy. virtual public void serve(King k) { k. when_happy += new Notify(happy); } public void happy(Object other) { Console. Write. Line(this + " is happy to hear that " + other + " is happy. "); } }. . . } 28

Delegates and Events • Delegate type definition: pointer to a function (to be called Delegates and Events • Delegate type definition: pointer to a function (to be called when a king changes his state) namespace Kingdom { delegate Object 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; } 29

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

Classes Citizen and Nobleman namespace Kingdom { … sealed class Citizen: Man { public Classes Citizen and Nobleman namespace Kingdom { … sealed class Citizen: Man { public Citizen(String name) : base(name) { } override public String To. String() { Citizen return "Citizen " + Name; sealed } } class Nobleman: Man { public Nobleman(String name) : base(name) { } override public String title() {return Name; } public Nobleman ill(Object other) { Console. Write. Line(this + " is sorry to hear that " + other Nobleman + " is ill. "); concrete return this; } override public void serve(King k) { base. serve(k); } } } k. when_ill += new Notify(ill); 31

Main Application static class Life { static void Main() { Life King R = Main Application static class Life { static void Main() { Life King R = new King("Richard"), static G = new King("George"); Citizen a = new Citizen("Al"), b = new Citizen("Bob"); Nobleman v = new Nobleman("Virgil"); a. serve(R); b. serve(G); v. serve(R); Richard G. serve(R); George } } R. ill(); R. become_happy(); Console. Write. Line("----"); G. become_ill(); G. become_happy(); Console. Write. Line("----"); Al Bob Virgil 32

Output Richard Scenario George 1. King Richard becomes ill 2. King Richard becomes happy Output Richard Scenario George 1. King Richard becomes ill 2. King Richard becomes happy 3. King George becomes happy Al Bob Virgil 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. Virgil 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. Virgil 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. ---33

Delegate Variance • Delegate definition: delegate Object Notify(King k); • Actual delegates: public Man Delegate Variance • Delegate definition: delegate Object Notify(King k); • Actual delegates: public Man happy(Object other) {…} public Nobleman 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. 34

Delegate Type Hierarchy using System; using System. Reflection; delegate Object My. Delegate. Type(Type o); Delegate Type Hierarchy using System; using System. Reflection; delegate Object My. Delegate. Type(Type o); public static class Delegate. Type. Hierarchy { private static String p. Name(Type t) { as before. . . } private static void ancestory(Object o){ as before… } public static void Main() { ancestory(new My. Delegate. Type(p. Name)); } } My. Delegate. Type inherits from System. Multicast. Delegate inherits from System. Object inherits from null 35

Summary – C# Unique Features • Properties and Indexers: implement fields with functions – 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 36