There is literature saying events are not heritable.
I made an code example, seems to me events a r e heritabel.
Maybe its something not really clear within oop world?
The example has 3 classes: cycel, bicycle, motorcycle and InvalidWhightEventArgs.
Cycel is the base, and there is declared the event InvalidWightEventHandler, occures if whight gets an invalid value.
The property whight is overwritten in the other classes, with intention. Cause the literature says futhermore, events rise only in those classes where they are declared.
So, the event in this example is only declared in cycle, but raises in all the others as well.
The code, Class Cycle:
Class BiCycleCode:public delegate void InvalidWightEventHandler(Cycle sender); public class Cycle { protected double mWight = 0; public event InvalidWightEventHandler InvalidWight; //Constructor public Cycle() { } //OnXx Methods protected virtual void OnInvalidWight(InvalidWhightEventArgs e) { if (InvalidWight != null) InvalidWight(this); } //Propertys public virtual double Wight { get {return mWight;} set { if (value >= 0) {mWight = value;} else { OnInvalidWight(new InvalidWhightEventArgs(value)); } } } public override string ToString() { return "Cycle=" + "Cycle\n" + ", Wight=" + Wight; } }
Class MotorCycleCode:public class BiCycle : Cycle { //Constructor public BiCycle() { } //Propertys public override double Wight { get { return mWight; } set { //other conditions if (value >= 10) { mWight = value; } else { OnInvalidWight(new InvalidWhightEventArgs(value)); } } } public override string ToString() { return "Cycle=" + "BiCyle\n" + ", Wight=" + Wight; } }
Class InvalidWhightEventArgsCode:public class MotorCycle: BiCycle { //Constructor public MotorCycle() { } //Propertys public override double Wight { get {return mWight;} set { //MotorCycle other conditions if (value >= 100) {mWight = value; } else { OnInvalidWight(new InvalidWhightEventArgs(value)); } } } public override string ToString() { return "Cycle=" + "MotorCyle\n" + ", Wight=" + Wight; } }
Class ProgrammCode:public class InvalidWhightEventArgs : EventArgs { // Fields private double mInvalidWhight; //Constructor public InvalidWhightEventArgs(double invalidWhight) { mInvalidWhight = invalidWhight; } //Propertys public double InvalidWhight { get { return mInvalidWhight; } } }
Code:class Program { static void Main(string[] args) { Cycle myC = new Cycle(); BiCycle myB = new BiCycle(); MotorCycle myM = new MotorCycle(); myC.InvalidWight += myB_InvalidWight; myB.InvalidWight += myB_InvalidWight; myM.InvalidWight += myB_InvalidWight; myC.Wight = -1; myB.Wight = 1; myM.Wight = 10; Console.ReadLine(); } private static void myB_InvalidWight(object sender) { Console.WriteLine("invalid wight: " + ((Object)sender).ToString()); } }




