123 not clear what the sense… of getting delegate objs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DelegateCovariance { class Program { public delegate Car ObtainCarDelegate(); public delegate SportsCar ObtainSportsCarDelegate(); public delegate Car ObtainVehicleDelegate(); public static Car GetBasicCar() { return new Car("123", 100, 55);} public static SportsCar GetSportsCar(){return new SportsCar("123", 100, 55);} static void Main(string[] args) { ObtainCarDelegate targetA = new ObtainCarDelegate(GetBasicCar); Car c = targetA(); Console.WriteLine("Obtained a {0} ",c); // Console.ReadLine(); ObtainSportsCarDelegate targetB = new ObtainSportsCarDelegate(GetSportsCar); SportsCar sc = targetB(); Console.WriteLine("Obtained a {0} ", sc); // Console.ReadLine(); //covariance here - it uses inheritance of Car and Sports Car ObtainVehicleDelegate targetA1 = new ObtainVehicleDelegate(GetBasicCar); Car c1 = targetA1(); Console.WriteLine("Obtained a {0} ", c1); ObtainVehicleDelegate targetB1 = new ObtainVehicleDelegate(GetSportsCar); Car c2 = targetB1(); Console.WriteLine("Obtained a {0} ", c2); Console.ReadLine(); } } public class Car { public int ID { get; set; } public int Speed { get; set; } public string Name { get; set; } public Car(string name, int speed, int id) { Name = name; Speed = speed; ID = id; } public Car() { } } public class SportsCar : Car { public SportsCar() { } public SportsCar(string name, int speed, int id) : base(name, speed, id) { } } class SomeClass { public delegate Car ObtainCarDelegate(); private ObtainCarDelegate CarlistOfHandlers; public void RegisterHandlerCarDelegate(ObtainCarDelegate method) { CarlistOfHandlers += method; } // delegate block public delegate void SomeDelegate(string Amessage); private SomeDelegate listOfHandlers; public void RegisterHandler(SomeDelegate method) { listOfHandlers += method; } public void UnRegisterHandler(SomeDelegate method) { listOfHandlers -= method; } //do something in class public void SomeMethod() { //some code if (listOfHandlers != null) { listOfHandlers("hello from delegate method"); } //some code } public void SomeCarMethod() { //some code if (listOfHandlers != null) { } //some code } } } |