1 / 43

Class, members, delegate, generic

Class, members, delegate, generic. Access modifiers. Príklad. class Vehicle : System.Object { private int privateInt; protected int protectedInt; public int publicInt; internal int internalInt; protected internal int piInt; }. Constructor method .

aspen-cook
Download Presentation

Class, members, delegate, generic

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Class, members, delegate, generic

  2. Access modifiers

  3. Príklad class Vehicle : System.Object { private int privateInt; protected int protectedInt; public int publicInt; internal int internalInt; protected internal int piInt; }

  4. 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. Peer constructor class Vehicle { public Vehicle() { // initialization here } public Vehicle(int fuelAmount) : this() { // do some other work } }

  6. 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. 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. 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. 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. Sealed class • Sealedclass nemôže byť dedené public sealed class MySealedClass { }

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

  12. 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. Interface

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

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

  16. 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. 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. 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. Explicit imlementation public class AmphibiousVehicle : ICar, IBoat { void IBoat.Go() { Console.WriteLine("IBoat.Go()... Floating"); } void ICar.Go() { Console.WriteLine("ICar.Go()... Driving"); } }

  20. 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. 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. Kombinácia dedičnosti aj interface class MyClass : BaseClass, IGraphicObject, IComparable, ICloneable { // Insert Implementation here }

  23. 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. 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. Použitie delegátov Deklarácia Vytvorenie instance Pridanie alebo odobranie metód Vyvolanie delegáta – invoke

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

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

  28. 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. 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. 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. // 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. Event – udalosť Event je špeciálny delegát, s niekolkými obmedzeniami

  33. 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. // 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. 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. 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. 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. Generic in .NET 2.0 FCL (Framework Class Library)

  39. 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. 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. 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. Generic constrains Umožňujú CLR porovnanie dvoch generických hodnôt Príklady constrains:

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

More Related