Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "YOUR LOGO Class, members, delegate, generic. YOUR LOGO Access modifiers ModifierExplanation privateThe member is visible only in the class. publicThe."— Presentation transcript:

1 YOUR LOGO Class, members, delegate, generic

2 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.)

3 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; }

4 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) { } }

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

6 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(){} }

7 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

8 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á

9 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

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

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

12 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; }

13 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)

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

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

16 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 }

17 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

18 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.)"); }

19 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"); }

20 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(); }

21 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)

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

23 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

24 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

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

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

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

28 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 );

29 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

30 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))

31 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); }

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

33 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

34 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; } }

35 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); }

36 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);

37 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... */ }

38 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

39 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. }

40 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. }

41 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()); }

42 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.

43 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; }


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

Similar presentations


Ads by Google