在C#中,可以通過事件來傳遞數據,其中EventArgs類用于封裝事件參數。下面是一個簡單的示例:
首先,定義一個包含事件的類:
public class DataEventArgs : EventArgs
{
public string Data { get; set; }
public DataEventArgs(string data)
{
Data = data;
}
}
public class DataPublisher
{
public event EventHandler<DataEventArgs> DataPublished;
public void PublishData(string data)
{
OnDataPublished(new DataEventArgs(data));
}
protected virtual void OnDataPublished(DataEventArgs e)
{
DataPublished?.Invoke(this, e);
}
}
然后,創建一個訂閱者類來處理事件:
public class DataSubscriber
{
public void Subscribe(DataPublisher publisher)
{
publisher.DataPublished += Publisher_DataPublished;
}
private void Publisher_DataPublished(object sender, DataEventArgs e)
{
Console.WriteLine("Received data: " + e.Data);
}
}
最后,在主程序中使用這些類:
public class Program
{
public static void Main(string[] args)
{
DataPublisher publisher = new DataPublisher();
DataSubscriber subscriber = new DataSubscriber();
subscriber.Subscribe(publisher);
publisher.PublishData("Hello, World!");
Console.ReadLine();
}
}
當調用publisher.PublishData("Hello, World!")
時,事件將被觸發,然后訂閱者類中的Publisher_DataPublished
方法將被執行,并打印出接收到的數據。