处理调用的通用方法

时间:2019-02-05 14:52:18

标签: c# .net

我已经厌倦了试图弄清楚何时何地需要调用。一遍又一遍地内联重写此代码很繁琐。我创建了以下方法来帮助解决此问题:

public void RunInvoked(object sender, Action method)
{
    Control This = sender as Control;

    if (This.InvokeRequired)
    {
        if (!This.IsHandleCreated) return;

        This.Invoke((MethodInvoker)delegate ()
        {
            method();
        });
    }
    else
    {
        method();
    }
}

(示例方法),我这样称呼它:

private void EnableButton(bool enable)
{
    RunInvoked(this, () =>
    {
        if (enable)
        {
            this.buttonSet.Enabled = true;
            this.buttonSet.ForeColor = Color.Black;
            this.buttonSet.BackColor = Color.LightBlue;
        }
        else
        {
            this.buttonSet.Enabled = false;
            this.buttonSet.ForeColor = Color.Gray;
            this.buttonSet.BackColor = SystemColors.ButtonFace;
        }

        this.buttonSet.Update();
    });
}

我只想确保这是合理的逻辑,并且在我开始在整个代码中实现之前,不要忽略我没有意识到的一些明显问题。如果您愿意的话,也希望对它的通用性有所帮助。谢谢!

0 个答案:

没有答案
相关问题