在C# WinForms中提升自定义事件,可以通过以下步骤实现:
EventHandler
或EventHandler<T>
,其中T
是一个自定义的事件参数类型,用于传递事件相关的数据。public class CustomEventArgs : EventArgs
{
public string Message { get; set; }
public CustomEventArgs(string message)
{
Message = message;
}
}
public class EventSource
{
public event EventHandler<CustomEventArgs> CustomEvent;
protected virtual void OnCustomEvent(CustomEventArgs e)
{
CustomEvent?.Invoke(this, e);
}
}
public class EventSubscriber
{
public EventSubscriber(EventSource eventSource)
{
eventSource.CustomEvent += OnCustomEvent;
}
private void OnCustomEvent(object sender, CustomEventArgs e)
{
Console.WriteLine($"Custom event raised: {e.Message}");
}
}
OnCustomEvent
方法来触发事件。public class EventSource
{
public void RaiseCustomEvent()
{
OnCustomEvent(new CustomEventArgs("Hello, world!"));
}
}
public static void Main(string[] args)
{
EventSource eventSource = new EventSource();
EventSubscriber eventSubscriber = new EventSubscriber(eventSource);
eventSource.RaiseCustomEvent();
}
这样,当事件源触发自定义事件时,事件订阅者的事件处理程序将被调用,从而实现了事件的提升。
领取专属 10元无门槛券
手把手带您无忧上云