This code consists of an interface delegate and a class hard disk the code is working perfectly but I am trying to understand on how delegates, classes, interfaces and events work quite frankly this is not my code but I want to learn from it, my question is strictly on how to call events and where did the programmer write them or declare them them in this code below please correct me if I’m wrong
This is a class sendevent or delegate though I’m not sure
namespace ConsoleApplication4
{
delegate void SendEventHandler(object sender, SendEventArgs args);
class SendEventArgs : EventArgs
{
public byte[] Buf;
public int ByteCount;
public object whom;
public SendEventArgs(byte[] Buf, int ByteCount, object whom)
{
this.Buf = Buf;
this.ByteCount = ByteCount;
this.whom = whom;
}
}
}
In my own understanding this is an interface name isata
interface ISata
{
//voltage +12В, +5В или +3.3В
Double Voltage { get; }
//transfer rate (bytes / sec)
Int64 DataTransferRate { get; }
event SendEventHandler SendEvent;
void Send(byte[] Buf, int ByteCount, object whom);
void OnReceive(object sender, SendEventArgs args);
void ConnectWith(ISata Device);
void Disconnect(ISata Device);
This is a class hardisk
namespace ConsoleApplication4
{
class HardDisk : ISata
{
string Id = "no id";
public Double Voltage
{
get
{
return 12;
}
}
public Int64 DataTransferRate
{
get
{
return 629145600;
}
}
public event SendEventHandler SendEvent;
public HardDisk(string Id)
{
this.Id = Id;
}
public override string ToString()
{
return "HD{" + Id + "}";
}
public void ConnectWith(ISata Device)
{
Device.SendEvent += OnReceive;
this.SendEvent += Device.OnReceive;
Console.WriteLine(this + " connected with device " + Device);
}
public void Disconnect(ISata ConnDev)
{
if (ConnDev != null)
{
this.SendEvent -= ConnDev.OnReceive;
ConnDev.SendEvent -= OnReceive;
Console.WriteLine(this + " disconnected from device " + ConnDev);
}
}
public void Send(byte[] Buf, int ByteCount, object whom)
{
if (SendEvent != null)
{
SendEvent(this, new SendEventArgs(Buf, ByteCount, whom));
}
}
public void OnReceive(object sender, SendEventArgs args)
{
if(args.whom == this)
Console.WriteLine(this + " received data from " + sender);
}
}
}
My question is that where did he declare the events and where was the event called?
This is where the event is declared:
This is where the event is subscribed to; when the event occurs, the
Device‘sOnReceivemethod will be called:This is where the event is unsubscribed from; it stops the method from being called when the event occurs:
This is where the event is “called”: