我正在尝试捕获触发了哪个事件。我有两个指向相同函数的事件CurrentLoan_LogEntryEvent
。在CurrentLoan_LogEntryEvent
内,如何确定实际触发了哪个事件:LogEntryAdded
或LogEntryChange
。
下面你会找到我的代码示例,我现在有了它。如果您对我的代码有任何疑问,请与我们联系。
CurrentLoan
是一个Loan
对象,它有两个事件。
public MyApplication()
{
ThirdPartyDLL.LoanOpened += new EventHandler(CurrentLoanOpened);
}
private void CurrentLoanOpened(object sender, EventArgs e)
{
ThirdPartyDLL.CurrentLoan.LogEntryAdded += CurrentLoan_LogEntryEvent;
ThirdPartyDLL.CurrentLoan.LogEntryChange += CurrentLoan_LogEntryEvent;
}
private void CurrentLoan_LogEntryEvent(object sender, LogEntryEventArgs e)
{
// When LogEntry was Added or Changed.
// How do I determine if LogEntryAdded or LogEntryChange was fired?
}
答案 0 :(得分:5)
如果要区分两个事件,则无法为多个事件附加单个方法。给他们不同的处理程序。
当您不关心事件来源的位置时,通常会为多个事件附加单个处理程序,但您始终希望在处理程序中执行相同的操作。
如果你有一些常用的逻辑要执行,你可以在处理程序中调用它。
private void CurrentLoanOpened(object sender, EventArgs e)
{
ThirdPartyDLL.CurrentLoan.LogEntryAdded += CurrentLoan_LogEntryAdded;
ThirdPartyDLL.CurrentLoan.LogEntryChange += CurrentLoan_LogEntryChange;
}
private void CurrentLoan_LogEntryAdded(object sender, LogEntryEventArgs e)
{
//LogEntryAdded fired
YourOptionalCommonMethodIfAny();
}
private void CurrentLoan_LogEntryChange(object sender, LogEntryEventArgs e)
{
//LogEntryChange fired
YourOptionalCommonMethodIfAny();
}
答案 1 :(得分:4)
你为什么不这样做:
private void CurrentLoanOpened(object sender, EventArgs e)
{
ThirdPartyDLL.CurrentLoan.LogEntryAdded += CurrentLoan_LogEntryAddedEvent;
ThirdPartyDLL.CurrentLoan.LogEntryChange += CurrentLoan_LogEntryChangeEvent;
}
private void CurrentLoan_LogEntryAddedEvent(object sender, LogEntryEventArgs e)
{
// First do what you must do specifically for added events
CurrentLoan_LogEntry(e);
}
private void CurrentLoan_LogEntryChangeEvent(object sender, LogEntryEventArgs e)
{
// First do what you must do specifically for changed events
CurrentLoan_LogEntry(e);
}
将一个处理程序绑定到多个事件,然后确定在该处理程序中执行的操作只会使事情过于复杂。
始终保持代码易于理解和更改。