简体   繁体   中英

Reuse event handler good practice in C#

In my current project, I am using four grid views in different tabs. As the system has developed, they have some shared methods, such as show a custom tooltip and a right click menu for when on rows.

I am now going through a code cleaning exercise. What I see below is that I now have four event handlers calling the same method. Is it OK to change the event handlers all to point directly to GridMenu, avoiding the extra code? Will this cause me problems later in development?

Obviously at present I am using the default even handler names.

private void grdEnquiriesLevel1_ShowGridMenu(object sender, GridMenuEventArgs e)
    {
        GridMenu(sender, e);
    }

    private void grdApplicantsLevel1_ShowGridMenu(object sender, GridMenuEventArgs e)
    {
        GridMenu(sender, e);
    }

    private void grdApplicationsLevel1_ShowGridMenu(object sender, GridMenuEventArgs e)
    {
        GridMenu(sender, e);
    }

    private void grdInterviewsLevel1_ShowGridMenu(object sender, GridMenuEventArgs e)
    {
        GridMenu(sender, e);
    }

    private void GridMenu(object sender, GridMenuEventArgs e)
    {
        GridView view = (GridView)sender;

        if (view.CalcHitInfo(e.Point).InRow)
            popupMenu1.ShowPopup(Cursor.Position);
    }

Instead of registering directly to GridMenu , create a general event handler named Grid_ShowGridMenu .

Just register to the same event handler for each grid, instead of creating a separate event handler per grid.

grdEnquiriesLevel1.ShowGridMenu += Grid_ShowGridMenu;
grdApplicantsLevel1.ShowGridMenu += Grid_ShowGridMenu;
grdApplicationsLevel1.ShowGridMenu += Grid_ShowGridMenu;
grdInterviewsLevel1.ShowGridMenu += Grid_ShowGridMenu;


private void Grid_ShowGridMenu(object sender, GridMenuEventArgs e)
{
    GridMenu((GridView)sender, e.Point); 
}

Now, instead of passing sender, e directly to GridMenu , pass only necessary values to GridMenu and change the signature of GridMenu so it can be more reusable .

private void GridMenu(GridView grid, Point hitPoint) 
{
    if (grid.CalcHitInfo(hitPoint).InRow)
        popupMenu1.ShowPopup(Cursor.Position);
}

As long as the event code is generic for all controls then this method is fine and clean.

If you start having major if/else or switch blocks in the code then maybe it is time for a re-think.

You should make a User Control that encapsulates your custom Grid. That way, all of your behavior will be encapsulated and reusable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM