430 likes | 543 Views
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 .
E N D
Príklad class Vehicle : System.Object { private int privateInt; protected int protectedInt; public int publicInt; internal int internalInt; protected internal int piInt; }
Constructor method • Zdedená trieda volá defaultne konštruktor triedy rodičovskej • Možnosť zmeny: • Specific base constructor class Car : Vehicle { public Car() : base(100) { } }
Peer constructor class Vehicle { public Vehicle() { // initialization here } public Vehicle(int fuelAmount) : this() { // do some other work } }
Hiding members class Vehicle { protected int fuelLevel = 100; public int Start(){} } class Boat : Vehicle { private new float fuelLevel = 50.0f; public new int Start(){} }
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
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á
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
Sealed class • Sealedclass nemôže byť dedené public sealed class MySealedClass { }
Abstract class Nemôžem vytvoriť inštancie tejto triedy Nemôže byť sealed
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; } }
Interface Interface popisuje kontrakt, ku ktoremu sa zaväzuje triede, že ho bude dodržiavať Popisuje ako budú dva objekty komunikovať
Interface Declaration interface IGraphicObject { void Translate(int dx, int dy); int Top { get; set; } int Left { get; set; } }
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 } } }
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
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.)"); } }
Explicit imlementation public class AmphibiousVehicle : ICar, IBoat { void IBoat.Go() { Console.WriteLine("IBoat.Go()... Floating"); } void ICar.Go() { Console.WriteLine("ICar.Go()... Driving"); } }
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(); }
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)
Kombinácia dedičnosti aj interface class MyClass : BaseClass, IGraphicObject, IComparable, ICloneable { // Insert Implementation here }
Delegáty a udalosti Delegát je trieda, ktorá zapúzdruje metódy Zoznam metód asociovaných s delegátom je invocation list
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
Použitie delegátov Deklarácia Vytvorenie instance Pridanie alebo odobranie metód Vyvolanie delegáta – invoke
Deklarácia • Deklarácia v namespace alebo triede // delegate method prototype delegate void MyDelegate(int x, int y);
Vytvorenie instance class MyClass { // delegate instantiation private MyDelegate myDelegate = new MyDelegate(SomeFun); // static method public static void SomeFun(int dx, int dy) { } }
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 );
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
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))
// 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); } }
Event – udalosť Event je špeciálny delegát, s niekolkými obmedzeniami
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
// 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; } } }
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); } }
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);
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... */ }
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. }
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. }
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()); } }
Generic constrains Umožňujú CLR porovnanie dvoch generických hodnôt Príklady constrains:
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; } }