YOUR LOGO Class, members, delegate, generic. YOUR LOGO Access modifiers ModifierExplanation privateThe member is visible only in the class. publicThe.

Slides:



Advertisements
Similar presentations
Generics Programming in C# Generics CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
Advertisements

OOP Abstraction Classes Class Members: Properties & Methods Instance (object) Encapsulation Interfaces Inheritance Composition Polymorphism Using Inheritance.
CS  C++ Function Pointers  C# Method References  Groundwork for Lambda Functions.
Writing Object Oriented Software with C#. C# and OOP C# is designed for the.NET Framework  The.NET Framework is Object Oriented In C#  Your access to.
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 7 th & 8 th Lecture Pavel Ježek.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Object Oriented Concepts
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 11 th Lecture Pavel Ježek
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
One of the most prevalent powerful programming languages.
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
1 Interfaces and Abstract Classes Chapter Objectives You will be able to: Write Interface definitions and class definitions that implement them.
C# Programming: From Problem Analysis to Program Design1 10 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
[ISRAR ALI] Hammad Khan. The namespace keyword is used to declare a scope. Making software components reusable can result in naming collisions (two classes.
C# Interfaces C# Class Version 1.0. Copyright © 2012 by Dennis A. Fairclough all rights reserved. 2 Interface  “A surface forming a common boundary between.
Module 8: Delegates and Events. Overview Delegates Multicast Delegates Events When to Use Delegates, Events, and Interfaces.
Advanced C# Types Tom Roeder CS fa. From last time out parameters difference is that the callee is required to assign it before returning not the.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
ITF11006.NET Generics. Generics - Sample Recent Generics - Characteristics Performance Type Safety Binary Code Reuse Code Bloat Naming Guidelines.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 11 th Lecture Pavel Ježek
Introduction to Object-Oriented Programming Lesson 2.
1 Principles revisited.NET: Two libraries: System.Collections System.Collections.Generics Data Structures and Collections.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Topics Instance variables, set and get methods Encapsulation
C# Interfaces and RTTI CNS 3260 C#.NET Software Development.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Module 5: Programming with C#. Overview Using Arrays Using Collections Using Interfaces Using Exception Handling Using Delegates and Events.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 2 nd Lecture Pavel Ježek
C# - OOP TTU IT College , Autumn SEMESTER Andres käver.
Static data members Constructors and Destructors
Classes and Inheritance
Ch 10- Advanced Object-Oriented Programming Features
Advanced Object-Oriented Programming Features
2.7 Inheritance Types of inheritance
Inheritance and Polymorphism
Module 5: Common Type System
Delegates and Events 14: Delegates and Events
Microsoft .NET 3. Language Innovations Pan Wuming 2017.
Chapter 5: Programming with C#
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
Structs.
CS360 Windows Programming
C# In many ways, C# looks similar to Java
OOP’S Concepts in C#.Net
Chapter 9 Inheritance and Polymorphism
Java Programming Language
Lecture 22 Inheritance Richard Gesick.
Classes & Objects: Examples
Delegates & Events 1.
CIS 199 Final Review.
Java Programming Language
Quiz Points 1 Rules Raise your hand if you know the question
Defining Interfaces using C#
Chapter 11 Inheritance and Encapsulation and Polymorphism
Advanced .NET Programming I 3rd Lecture
CSG2H3 Object Oriented Programming
Interfaces, Enumerations, Boxing, and Unboxing
Chapter 5 Classes.
Presentation transcript:

YOUR LOGO Class, members, delegate, generic

YOUR LOGO Access modifiers ModifierExplanation privateThe member is visible only in the class. publicThe member is visible to any inheritor or user of the class. protectedThe member is visible only to inheritors of the class. internalThe member is visible inside of the assembly (or program). protected internal The member is visible inside of the assembly or to inheritors (inside or outside the assembly.)

YOUR LOGO Príklad MemberVisible to Derived Class privateIntNo protectedIntYes publicIntYes internalIntYes piIntYes class Vehicle : System.Object { private int privateInt; protected int protectedInt; public int publicInt; internal int internalInt; protected internal int piInt; }

YOUR LOGO Constructor method  Zdedená trieda volá defaultne konštruktor triedy rodičovskej  Možnosť zmeny: -Specific base constructor class Car : Vehicle { public Car() : base(100) { } }

YOUR LOGO Peer constructor class Vehicle { public Vehicle() { // initialization here } public Vehicle(int fuelAmount) : this() { // do some other work } }

YOUR LOGO Hiding members class Vehicle { protected int fuelLevel = 100; public int Start(){} } class Boat : Vehicle { private new float fuelLevel = 50.0f; public new int Start(){} }

YOUR LOGO Hidding members  Nutne použit new, bez toho compiler vytvorí warning, nie error.  Možnosť skrývať, data members, properties, events, methods  Je možné v dedenej triede použiť iný typ Vehicle v = new Boat(); v.Start();  Príklad volá Start() pre Vehicle triedu

YOUR LOGO Overriding members class Vehicle { public virtual int Start(){} } class Boat : Vehicle { public override int Start(){} } Príklad: Vehicle v = new Boat(); v.Start();  Volám Start() z Boat triedy.  Nutné používať virtual a override klúčové slová

YOUR LOGO Override  Nie je možne override static členov  Private členovia nemôžu byť virtual  Nutná zhodnosť typov  Nie je možné zmeniť access modifier počas override

YOUR LOGO Sealed class  Sealed class nemôže byť dedené public sealed class MySealedClass { }

YOUR LOGO Abstract class  Nemôžem vytvoriť inštancie tejto triedy  Nemôže byť sealed 

YOUR LOGO abstract class Shape { // class fields protected int x; protected int y; protected int width; protected int height; // non-abstract method public void SetPosition(int x, int y) { this.x = x; this.y = y; } // abstract method public abstract double CalculateArea(); // abstract properties public abstract int Width { get; set; } public abstract int Height { get; set; }

YOUR LOGO Interface TypesContainsCapability Public InterfaceImplementation (Code) Instantiate (Create an object)A class can... ClassYes Inherit (Only 1 class) Abstract Class YesYes/NoNo Inherit (Only 1 class) -- Abstract class are generally used as base classes for derived classes. InterfaceYesNo Implement (0 or more interfaces)

YOUR LOGO Interface  Interface popisuje kontrakt, ku ktoremu sa zaväzuje triede, že ho bude dodržiavať  Popisuje ako budú dva objekty komunikovať

YOUR LOGO Interface Declaration interface IGraphicObject { void Translate(int dx, int dy); int Top { get; set; } int Left { get; set; }

YOUR LOGO Interface implementation class GraphicClass : IGraphicObject { public void Translate(int dx, int dy) { // implementation of Translate } public int Top { get { // implementation of Top get } set { // implementation of Top set } public int Left { get { // implementation of Left get } set { // implementation of Left set }

YOUR LOGO Interface facts  No access specific – always public  Nemajú kód  Implementace interface musí byť public  Možnosť implementace jedného a viac interface na rozdiel od dedičnosti

YOUR LOGO Implicit imlementation public interface ICar { void Go(); } public interface IBoat { void Go(); } public class TheInfamousCarBoat : ICar, IBoat { public void Go() { Console.WriteLine("Going... (Wet or dry? I don't know.)"); }

YOUR LOGO Explicit imlementation public class AmphibiousVehicle : ICar, IBoat { void IBoat.Go() { Console.WriteLine("IBoat.Go()... Floating"); } void ICar.Go() { Console.WriteLine("ICar.Go()... Driving"); }

YOUR LOGO Use of explicit Implementation static void Main() { AmphibiousVehicle av = new AmphibiousVehicle(); // calls the IBoat.Go() method implementation (av as IBoat).Go(); // calls the ICar.Go() method implementation (av as ICar).Go(); }

YOUR LOGO Interface inheritance interface IGraphicObject : System.Collections.IComparable { void Translate(int dx, int dy); int Top { get; set; } int Left { get; set; }  Musime implementovat v triede aj int CompareTo(object obj)

YOUR LOGO Kombinácia dedičnosti aj interface  class MyClass : BaseClass, IGraphicObject, IComparable, ICloneable  {  // Insert Implementation here  }

YOUR LOGO Delegáty a udalosti  Delegát je trieda, ktorá zapúzdruje metódy  Zoznam metód asociovaných s delegátom je invocation list

YOUR LOGO Delegate  Eventy – udalost sú založené na delegátoch  Event handler metóda je pridaná do invocation listu delegáta  Delegát je objekt a môže byť predaný ako odkaz v atribúte metódy  Metódy delegáta môžu byť volané asynchronne, nemusia čakať na ukončenie

YOUR LOGO Použitie delegátov 1.Deklarácia 2.Vytvorenie instance 3.Pridanie alebo odobranie metód 4.Vyvolanie delegáta – invoke

YOUR LOGO Deklarácia  Deklarácia v namespace alebo triede // delegate method prototype delegate void MyDelegate(int x, int y);

YOUR LOGO Vytvorenie instance class MyClass { // delegate instantiation private MyDelegate myDelegate = new MyDelegate(SomeFun); // static method public static void SomeFun(int dx, int dy) { }

YOUR LOGO Pridanie a odobranie metód // Add a method myDelegate += new MyDelegate( mc.SomeMethod ); // Remove a method myDelegate -= new MyDelegate( mc.SomeMethod ); // Populate the invocation list myDelegate = new MyDelegate( mc.SomeMethod ) + new MyDelegate( mc.SomeOtherMethod );

YOUR LOGO Pridanie a odobranie metód  Sú vykonané všetky metódy po poradí  Je možné pridať metódu viac krát  Ak sa odoberie tak s odoberie posledný výskyt  Ak chcem odobrať neexistujúcu metódu tak sa nestane nič, ani error

YOUR LOGO Vyvolanie delegáta myDelegate(100, 50);  Spustí metódu alebo metódy v invocation liste  Nutnosť si overiť či je niečo v invocation list: (if(myDelegate != null))

YOUR LOGO // delegate declaration delegate void MyDelegate(int x, int y); class MainClass { private MyDelegate myDelegate; static void Main() { MainClass mainClass = new MainClass(); // instantiate a delegate using an instance method myDelegate = new MyDelegate(mainClass.MainClassMethod); } private void MainClassMethod(int x, int y) { } public void FireDelegate() { // invoke the delegate if (myDelegate != null) myDelegate(100, 50); }

YOUR LOGO Event – udalosť  Event je špeciálny delegát, s niekolkými obmedzeniami

YOUR LOGO Events  Publisher robí expose delegatu, tým by umožnil že každý môže urobiť invoke delegátu, prípadne zmeniť metódy  Slovom event zabezpečíme, že delegát môže byť iba subscribed, alebo unsubscribed

YOUR LOGO // declare a delegate (this will be our event delegate) public delegate void SomethingHappened(); class MyEventWrapper { // create an instance of this delegate // use the event keyword private event SomethingHappened somethingHappened; // fire the event when appropriate public void WhenSomethingHappens() { // only fire if someone has subscribed if (somethingHappened != null) somethingHappened(); } // expose the event public event SomethingHappened SomethingHappenedEvent { add { somethingHappened += value; } remove { somethingHappened -= value; } }

YOUR LOGO class SubscriberClass { private void SomethingHappensEventHandler() { // handle the event here } static void Main() { // create a subscriber instance SubscriberClass subscriber = new SubscriberClass(); // create a publisher instance MyEventWrapper publisher = new MyEventWrapper(); // subscribe to the event publisher.SomethingHappenedEvent += new SomethingHappened(subscriber.SomethingHappensEventHandler); }

YOUR LOGO Generic type Je taký typ o ktorom počas kompilácie neviem aký bude, až runtiem ho určí. Príklady použitia: // Generic Class: public class MyGenericClass {} // Generic Method: public void MyGenericMethod(T type) {} // Generic Interface: public interface MyGenericInterface {} // Generic Delegate: public delegate void MyGenericDelegate(T type);

YOUR LOGO namespace WhatsNew20Generics { class Program { static void Main(string[] args) { MyGeneric myGeneric = new MyGeneric(90210); MyGeneric myGeneric2 = new MyGeneric("Hello World!"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } // T is the generic type: public class MyGeneric { public MyGeneric(T type) { // We don't know what the type is, but we'll find out here: Console.WriteLine("Type of 'T' is {0}.", typeof(T).ToString()); } /* The following console output should be produced when this application is executed: Type of 'T' is System.Int32. Type of 'T' is System.String. Press any key to continue... */ }

YOUR LOGO Generic in.NET 2.0 FCL (Framework Class Library) Generic Class/InterfaceDescriptionNon-Generic Equivalent Collection, ICollection Provides the base class for a generic collection.CollectionBase, ICollection Comparer, IComparer, IComparable Compares two objects of the same generic type for equivalence and for sorting. Comparer, IComparer, IComparable Dictionary, IDictionary Represents a collection of key/value pairs that are organized based on the key.Hashtable, IDictionary Dictionary.KeyCollectionRepresents the collection of keys in a Dictionary.None. Dictionary.ValueCollectionRepresents the collection of values in a Dictionary.None. IEnumerable, IEnumerator Represents a collection that can be iterated using foreach.IEnumerable, IEnumerator KeyedCollection Represents a keyed collection.KeyedCollection LinkedList Represents a doubly linked list.None. LinkedListNode Represents a node in a LinkedList.None. List, IList Implements the IList interface using an array whose size is dynamically increased as required. ArrayList, IList Queue Represents a first-in, first-out collection of objects.Queue ReadOnlyCollection Provides the base class for a generic read-only collection.ReadOnlyCollectionBase SortedDictionary Represents a collection of key/value pairs that are sorted by key based on the associated IComparer implementation. SortedList Stack Represents a simple last-in-first-out (LIFO) collection of objects.Stack

YOUR LOGO Using non Generic ArrayList System.Collections.ArrayList arrayList = new System.Collections.ArrayList(); // 100 integer values will be stored as // objects in the ArrayList by casting/boxing: for (int i = 1; i <= 100; i++) arrayList.Add(i); // Now, let's retrieve the values from each type of collection: // Retrieve the values from the ArrayList: foreach (int i in arrayList) { // the Objects in arrayList are // cast to Int32 implicitly. }

YOUR LOGO Using Generic System.Collections.Generic.Collection genericCollection = new System.Collections.Generic.Collection(); // 100 integer values will be stored as // Int32 in the Collection<> without casting/boxing: for (int i = 1; i <= 100; i++) genericCollection.Add(i); // Retrieve the values from the Collection<>: foreach (int i in genericCollection) { // No need for the CLR to cast because // the underlying values are already Int32. }

YOUR LOGO Generic constrains static void Main(string[] args) { MyGenericClassConstrained.Compare("Hello World!", "Hello World!"); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } // This Generic will enforce a constraint that requires // the type is a reference type: public class MyGenericClassConstrained where T : class { public static void Compare(T someType, String someString) { if (someType == someString) Console.WriteLine("someType is equal to someString."); else Console.WriteLine("someType is not equal to someString"); Console.WriteLine("someType = {0}", someType.ToString()); }

YOUR LOGO Generic constrains  Umožňujú CLR porovnanie dvoch generických hodnôt  Príklady constrains: ConstraintDescription where T: structThe type argument must be a value type. where T : classThe type argument must be a reference type. where T : new() The type argument must have a public parameterless constructor. When used in conjunction with other constraints, the new() constraint must be specified last. where T : The type argument must be or derive from the specified base class. where T : The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.

YOUR LOGO Default public class MyClassWithDefault { public static T GetDefaultValue() { T result = default(T); // Will return 0 if a value type and // null if a reference type: return result; }