我正在创建具有一些我想在整个程序中使用的功能的基本Object类。我想包括的功能之一是通用的TriggerEvent函数,该函数假设在触发传入的事件之前进行一些基本检查:
/// <summary>
/// Executes the specified event if one of several internal conditions are met:
/// 1. The event is not null
/// 2. The DisableEvents property is not enavled
/// </summary>
/// <param name="eventProcedure">Event to execute</param>
/// <param name="e">Event arguments object (or null if none specified)</param>
protected void TriggerEvent(EventHandler<EventArgs> eventProcedure, EventArgs e = null)
{
if (eventProcedure != null)
{
if (!DisableEvents)
{
eventProcedure(this, e);
}
}
}
我遇到麻烦的地方是,我希望能够将通用EventHandlers传递给此函数,以便我也可以处理可能采用各种形式的EventArgs对象参数的事件。例如,我有一个这样的人:
/// <summary>
/// Used with the PrintMessage Event
/// </summary>
public class MessageEventArgs : EventArgs
{
public MessageEventArgs(string messageText)
{
MessageText = messageText;
}
public string MessageText { get; private set; }
}
以及相关事件:
public event EventHandler<MessageEventArgs> PrintMessage;
例如,此事件将允许我将消息传递给父对象。但我也希望能够将TriggerEvent函数用于可能与其他自定义Event args对象相关联的事件:
public event EventHandler<CustomEventArgs> SomeEvent;
public event EventHandler<EventArgs> SomeNormalEvent;
,然后可以使用TriggerEvent函数执行其中的任何一个:
TriggerEvent(PrintMessage, new MessageEventArgs(textToSend));
TriggerEvent(SomeEvent, ExistingCustomEventArgs);
TriggerEvent(SomeNormalEvent);
但是当我尝试使用TriggerEvent函数调用例如说以下内容的PrintMessage事件时出现错误:
Argument 1: Cannot convert from 'System.EventHandler<TestProject.MessageEventArgs>' to 'System.EventHandler<System.EventArgs>'
如何修改TriggerEvent函数,以便可以使用它检查和执行多种类型的事件?
答案 0 :(得分:0)
我可以想到两种方式。
protected void TriggerEvent(Action<EventArgs> eventProcedure, EventArgs e = null)
if (eventProcedure != null && !DisableEvents)
{
eventProcedure(e);
}
或者只是...
protected void TriggerEvent(Action eventProcedure)
if (eventProcedure != null && !DisableEvents)
{
eventProcedure();
}
,其用法类似于:TriggerEvent(() => MyEvent?.Invoke(this, new MyEventArgs(...)))
protected void TriggerEvent<T>(EventHandler<T> eventProcedure, T e = null) where T : EventArgs
if (eventProcedure != null && !DisableEvents)
{
eventProcedure(this, e);
}