Skip to main content
 首页 » 编程设计

c#之如何处理顺序调用事件处理程序

2024年02月23日16mfrbuaa

在我重新发明轮子之前......

这只是一个描述问题的示例 -- 假设您有一个收集了一些数据的后端,以及显示该集合中的一项的前端。

在后端,我有 ItemIndex——只要它发生变化,它就会触发 OnScroll 事件。

我还有 AddNewItem 方法,它在集合的末尾添加新项目。该方法的结尾是调用 OnNewItem 事件处理程序。

关键是——在 AddNewItem 中,我必须更改 ItemIndex,这会触发 OnScroll。如果前端显示所选项目,则 (!) OnScroll 和 OnNewItem 的接收者之一。

在这种情况下,它会被调用两次(不好)。一种解决方案是更改 item_index 而不是 ItemIndex,这样可以防止 OnScroll,但我不喜欢它,因为 ItemIndex 不再充当黑盒。

是否有任何已建立的顺序触发事件模式,并且只发送“重要”事件(此处:OnNewItem 覆盖 OnScroll)?我的想法是定义一个事件范围,而不是直接发送事件,只需注册它们以进行发送,并在范围结束时对它们进行排序并发送所需的。

一般来说——问题——我应该如何处理潜在的顺序事件触发。使用内部机制来避免发送冗余事件?忽略开销? ...?

请您参考如下方法:

答案对我来说似乎很明显,尽管我很容易漏​​掉一些东西:

private bool IsAdding { get; set; } 
private int item_index; 
private IList m_collection; 
 
public void AddNewItem(object item) 
{ 
    if (item == null) 
    { 
        throw new Exception("Cannot add null item."); // little bit of contracting never hurts 
    } 
 
    m_collection.Add(item); 
    IsAdding = true; 
    ItemIndex = collection.Count - 1; //I'm just making assumptions about this piece but it is not important how you decide what your index is to answer the question 
 
    if (OnNewItem != null) 
    { 
       OnNewItem(this, EventArgs.Empty);  
    } 
} 
 
public int ItemIndex 
{ 
   get { return item_index =; } 
   set 
   { 
       item_index = value; 
       if (!IsAdding && OnScroll != null) //won't double fire event thanks to IsAdding 
       { 
           OnScroll(this, EventArgs.Empty); 
       } 
       IsAdding = false; //need to reset it 
   } 
} 

我要注意的一件事是,您提到只是直接更改 item_index 但这不会有黑盒行为。嗯,黑盒子很好……但这个术语只适用于与我们一直在讨论的这个类交互的对象。

您应该感到有能力在自己的类(class)中使用类(class)的内部结构。对自身内部的项目进行黑盒处理不是好的 OOP。如果您这样做,那么您的类(class)可能存在设计问题,应该将其拆分为多个类(class)。