在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
方法将被执行,并打印出接收到的数据。