这段代码由一个接口委托和一个类硬盘组成,代码运行良好,但我试图了解委托、类、接口和事件是如何工作的,坦率地说,这不是我的代码,但我想从中学习,我的问题严格说明如何调用事件以及程序员在哪里编写或在下面的代码中声明它们,如果我错了,请纠正我
这是一个类发送事件或委托,虽然我不确定
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;
}
}
}
以我自己的理解,这是一个接口名称 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);
这是一个类硬盘
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);
}
}
}
我的问题是,他在哪里宣布了这些事件以及事件是在哪里调用的?