A cleaner way to automatically call one method after another?

前端 未结 7 1355
北荒
北荒 2021-01-18 02:28

Is it possible to design a method in such a fashion, that it knows it must automatically call a next method in succession upon exiting?

In the following example, I m

相关标签:
7条回答
  • 2021-01-18 03:02

    You could encapsulate the changes which would cause the form to refresh into form-level properties.

    For instance,

    private bool _showPriorityLine;
    private bool ShowPriorityLine
    {
        get { return _showPriorityLine; }
        set
        {
            _showPriorityLine = value;
            Refresh();
        }
    }
    

    Then your event would just be

    private void PriorityLine_Click(object sender, EventArgs e)
    {
        ShowPriorityLine = !ShowPriorityLine;
    }
    

    Of course, that only cleans up your code if you have several events manipulating the same variables that cause the form to need refreshing.

    0 讨论(0)
  • 2021-01-18 03:03

    Don't call Refresh, call Invalidate. The mechanism you need is already built into Windows. Calling Invalidate simply makes a note that the window needs repainting. The operating system will eventually post a WM_PAINT message (typically after the root DispatchMessage call finishes, but the exact implementation is irrelevant).

    0 讨论(0)
  • 2021-01-18 03:08

    Use a property that calls Refresh in the setter.

    0 讨论(0)
  • 2021-01-18 03:11

    Sounds like what you want is Aspect Oriented Programming, there are a number of different frameworks to enable you to have stuff "magically" happen after some set of methods have run, have a look here AOP programming in .Net?

    0 讨论(0)
  • 2021-01-18 03:16

    Something like this:

    private void RefreshAfter(Action action)
        {
            action();
            Refresh();
        }
    

    UPDATED TO MAKE IT MORE OBVIOUS:

        private void DoSomeUiShiznit(Action action)
        {
            action();
            // other parts of the code don't realize that Refresh has to be called.
            // But that's cool. I got it covered.
            Refresh();
        }
    
        private void PriorityLine_Click(object sender, EventArgs e)
        {
            DoSomeUiShiznit(() => { _showPriorityLine = !_showPriorityLine; });
        }
    

    UPDATE -- Just a message to the down-voters:

    What some of you are too blind to see is that this is not all that different from:

    [SomeRefreshAttribute]  
    private void PriorityLine_Click(object sender, EventArgs e)  
    {
        _showPriorityLine = !_showPriorityLine;  
    }  
    

    Except that it is simpler, and doesn't require adding another framework to the solution. And yet the other answer suggesting as much don't get down-voted!

    What's wrong with you people?

    0 讨论(0)
  • 2021-01-18 03:17

    I'm not aware of any really clean way. One method would be to use PostSharp.

    0 讨论(0)
提交回复
热议问题